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
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:
You have cross-domain issue, so you need to use JSONP so change your jquery method as below
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.
$.getJSON("http://xx.xxx.xxx.xx/rest/user.json?jsoncallback=?",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
jQuery Manual: http://api.jquery.com/jQuery.getJSON/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With