嗨,我正在尝试通过使用这段代码从远程主机读取json。
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://50.116.19.49/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>
问题是,当我在浏览器中键入URL时,我从中获取json。但是无法使用上述jquery方法获取json。
有人可以在这方面提供帮助。谢谢
您有跨域问题,因此您需要使用JSONP,因此请如下更改jquery方法
如果URL包含字符串“ callback =?” (或类似的定义,服务器端API),则该请求将被视为JSONP。
$.getJSON("http://xx.xxx.xxx.xx/rest/user.json?jsoncallback=?",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
不允许跨域查询。有关可能的解决方法,请参见ajax jquery: can't get json/xml from other domain。另一种方法是使用同一域上的代理将本地查询代理到远程主机。