简体   繁体   English

使用jQuery消费JSON

[英]Consume JSON using jQuery

I am developing a website which consume json from external url, i tried this but i got a error 我正在开发一个使用来自外部URL的json的网站,我尝试了此操作但出现错误

XMLHttpRequest cannot load http://reuniyo.com/tst/json.php. Origin null is not allowed by Access-Control-Allow-Origin XMLHttpRequest cannot load http://reuniyo.com/tst/json.php. Origin null is not allowed by Access-Control-Allow-Origin . XMLHttpRequest cannot load http://reuniyo.com/tst/json.php. Origin null is not allowed by Access-Control-Allow-Origin

Below is the code I used. 下面是我使用的代码。

var url="http://reuniyo.com/tst/json.php";
jQuery.support.cors = true;
$("#success").load(url, function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});

Please help me. 请帮我。 Thanks in advance 提前致谢

Assuming that the remote URL is not in the same domain as the web site you're developing, uou need to either: 假设远程URL与您正在开发的网站不在同一个域中,则您需要:

  1. use JSONP if the remote API supports it (my tests suggest that it doesn't) 如果远程API支持JSONP,则使用JSONP (我的测试表明不支持)

  2. have the remote site add Access-Control-Allow-Origin: * to their response headers 让远程站点将Access-Control-Allow-Origin: *到其响应头中

If neither of those are possible you're out of luck - these rules are in there to prevent cross-origin scripting attacks. 如果这两种方法都不可行,那么您很不走运-这些规则可以防止跨域脚本攻击。

json.php的顶部添加此行

header('Access-Control-Allow-Origin: *');

Don't try to develop direct from your local file system, it creates all kinds of permissions problems. 不要尝试直接从本地文件系统进行开发,它会引起各种权限问题。 Move your development site to an http server (you can install one locally if you like). 将您的开发站点移动到http服务器(如果愿意,可以在本地安装一个)。

You also need to make sure that the host name you are accessing the site from has permission from reuniyo.com to make Ajax requests to it (using the aforementioned Access-Control-Allow-Origin HTTP header). 您还需要确保从其访问站点的主机名具有reuniyo.com的许可,可以向其发出Ajax请求(使用上述Access-Control-Allow-Origin HTTP标头)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM