【问题标题】:Get json data from another domain(cross domain)从另一个域(跨域)获取json数据
【发布时间】:2012-10-07 20:39:33
【问题描述】:

我是 jquery 新手,不知道从另一个域(跨域)获取 json 数据。

function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    xhr = null;
}
return xhr;
}

var request = createCORSRequest("get", "http://www.stackoverflow.com/");
if (request){
request.onload = function() {
    // ...
};
request.onreadystatechange = handler;
request.send();
}

我从这里Ways to circumvent the same-origin policy找到了这个程序

也就是说通过上面的代码我们可以访问跨域的json数据。

我复制了代码。这是说处理程序是未定义的

我不知道如何定义处理程序。

我也不知道在 request.onload 里面写什么

我将在哪里得到 json 结果

请帮忙

提前致谢

【问题讨论】:

    标签: asp.net jquery cross-domain


    【解决方案1】:

    处理程序是一个函数

    应该是这样的

    function handler(){
       var response = xhr.responseText;
       // do more with your response.
    }
    

    你的 xhr 也应该在函数 createCORSrequest 之外定义。

    见docs on XDR

    我知道你说你是 jquery 的新手,但你也应该看看 $.getJSON。它更容易。

    【讨论】:

    • 嗨 Praneeta 我正在尝试访问其他域数据。但它显示错误 XMLHttpRequest 无法加载 192.168.10.13:8080。 Access-Control-Allow-Origin 不允许来源localhost。如何解决这个问题。
    • 您必须添加 'Response.AppendHeader("Access-Control-Allow-Origin", "*");'到您的服务器端代码。在此页面上找到它http://stackoverflow.com/q/6516591/1028488 $.getJson 可用于访问来自不同域的数据(我一直使用它),但我不确定 IE 是如何处理它的。
    • 此外,一旦您在 localhost 上完成测试并将其移动到服务器,您可以将访问控制从 * 更改为您的域名(安全性)
    • 我还发现 jQuery.XDomainRequest.js (github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest) 很有帮助
    • Click Here 这是我要获取的数据。我尝试了所有可能的方法,但没有成功。请帮助从该 URL 检索数据。
    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2013-12-28
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多