XMLHttpRequest无法使用jQuery加载URL

Zak*_*ria 55 jquery json cross-domain cors

我正试图从"远程"网站获取一些json数据.我在99000端口上运行我的Web服务然后,我在99001端口上启动我的网站(http:// localhost:99001/index.html).

我收到以下消息:

    XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons. Origin http://localhost:99001 is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

即使我将我的网页作为HTML文件启动,我也会这样:

    XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons.Origin null is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

Web服务返回数据.我尝试捕获这样的数据项:

var url = "http://localhost:99000/Services.svc/ReturnPersons";
$.getJSON(url, function (data) {
success: readData(data)
});
function readData(data) {
    alert(data[0].FirstName);
}
Run Code Online (Sandbox Code Playgroud)

而我正试图得到这种结构:

[{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}]
Run Code Online (Sandbox Code Playgroud)

你知道我为什么会收到这个错误吗?

Cha*_*eaf 39

你不能做一个XMLHttpRequest交叉域,唯一的"选项"是一种名为JSONP的技术,它归结为:

要启动请求:<script>使用远程URL 添加新标记,然后确保远程URL返回调用回调函数的有效javascript文件.有些服务支持此功能(并允许您在GET参数中命名回调).

另一个简单的方法是在本地服务器上创建一个"代理",它获取远程请求,然后将其"转发"回你的javascript.

编辑/添加:

我看到jQuery通过检查URL是否包含"callback =?"来内置对JSONP的支持.(jQuery将用实际的回调方法替换?)但是您仍然需要在远程服务器上处理它以生成有效的响应.

  • 我通过添加"&callback =?"解决了这个问题.到URL.谢谢! (9认同)
  • Charles Leaf,其实你错了.还有另一个"选项",称为CORS.在此处查看如何启用它:http://enable-cors.org/ (2认同)

Sla*_*lav 34

在新的jQuery 1.5中,您可以使用:

$.ajax({
    type: "GET",
    url: "http://localhost:99000/Services.svc/ReturnPersons",
    dataType: "jsonp",
    success: readData(data),
    error: function (xhr, ajaxOptions, thrownError) {
      alert(xhr.status);
      alert(thrownError);
    }
})
Run Code Online (Sandbox Code Playgroud)

  • 不应该只是"成功:readData"? (4认同)
  • 我收到一个错误,因为SyntaxError:意外的令牌: (2认同)

Hug*_*lpz 19

提供3种工作解决方案.

给定一个外部JSON:

myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Run Code Online (Sandbox Code Playgroud)

解决方案1:$ .ajax()+ jsonp:

$.ajax({
  dataType: "jsonp",
  url: myurl ,
  }).done(function ( data ) {
  // do my stuff
});
Run Code Online (Sandbox Code Playgroud)

解决方案2:$ .ajax()+ json +&calback =?:

$.ajax({
  dataType: "json",
  url: myurl + '&callback=?',
  }).done(function ( data ) {
  // do my stuff
});
Run Code Online (Sandbox Code Playgroud)

解决方案3:$ .getJSON()+ calback =?:

$.getJSON( myurl + '&callback=?', function(data) {
  // do my stuff
});
Run Code Online (Sandbox Code Playgroud)

文件:http://api.jquery.com/jQuery.ajax/,http://api.jquery.com/jQuery.getJSON/


小智 6

找到了一个我不相信的可行解决方法.

以下是对该问题的详细描述:http: //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

基本上只要你使用表单/ url编码/纯文本内容类型就可以了.

$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: "http://localhost/endpoint",
    data: JSON.stringify({'DataToPost': 123}),
    success: function (data) {
        alert(JSON.stringify(data));
    }
});     
Run Code Online (Sandbox Code Playgroud)

我在ASP.NET WebAPI2中使用它.所以在另一端:

public static void RegisterWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
Run Code Online (Sandbox Code Playgroud)

这样,在解析纯文本内容类型时会使用Json格式化程序.

并且不要忘记在Web.config中:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>    
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.