Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Jquery Get json from remote host

Hi i am trying to read json from a remote host by using this piece of code.

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://xx.xxx.xxx.xx/rest/user.json",function(result){
  $.each(result, function(i, field){
    $("div").append(field + " ");
      });
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>
<div></div>

</body>
</html>

The problem is when i type the url in browser i get json from it. But failed to get json by using the above jquery method.

Can someone help in this regard. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am gong to assume this page is not being served from the site that hosts the JSON.

You are attempting to make a cross-domain request, which most(?) browsers to do allow. You are encountering what is called the same-origin policy of the browser. It is a security measure built into the browser. It will not allow you to make an XHR request to a location that is not on the same origin as the requesting page.

There are a few ways around this:

  1. Use a server-side proxy to make the request
  2. use JSONP to make the request (See GBD's answer)
  3. Look into CORS

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...