jQuery的Ajax和的getJSON请求创下的访问控制,允许原产地问题 [英] jQuery ajax and getJSON requests hitting access-control-allow-origin issues

查看:111
本文介绍了jQuery的Ajax和的getJSON请求创下的访问控制,允许原产地问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用从不同的服务器获取文件jQuery的 $。阿贾克斯 $。的getJSON ,但我打了的访问控制,允许原产地墙,和JSONP选项似乎并不为我工作。

I'm attempting to grab a file from a different server using jquery's $.ajax or $.getJSON, but I'm hitting the access-control-allow-origin wall, and the jsonp options don't seem to work for me.

该网站使用jQuery 1.5.1。

The site is using jQuery 1.5.1.

下面是我的三个测试:

使用基本$阿贾克斯,该请求的URL从来没有回调= 附:??

Using basic $.ajax, the url requested never has ?callback=? appended:

$.ajax({
    url: url,
    datatype: 'jsonp',
    error: function(){console.log('error');},
    success: function(){console.log('success');}
});

使用基本$就与企图的黑客,仍然获得跨站点的问题:

Using basic $.ajax with an attempted hack, still get cross-site issues:

$.ajax({
    url: url + '.jsonp?callback=?',
    datatype: 'jsonp',
    error: function(){console.log('error');},
    success: function(){console.log('success');}
});

使用$ .getJSON,击败了跨站点的问题,但错误的情况下永远不会触发:

Using $.getJSON, beats the cross site issues, but the error case is never triggered:

$.getJSON(url + '?callback=?',
    function(data){
        console.log('success');
    })
    .error(function(){
        console.log('error');
    })
    .success(function(){
        console.log('success!');
    });

任何人都看到我在做什么错了?最后,我想测试一下,看看如果该URL存在,并做一些事情上的错误,如果它没有。

Anyone see what I'm doing wrong? In the end, I'm trying to test to see if the url exists, and do something on error if it doesn't.

修改:网址我试图访问不存在。我期待在错误的情况下被触发。

Edit: The url I'm attempting to access does not exist. I'm expecting the error case to be triggered.

推荐答案

为了能够使用JavaScript访问外部资源。远程资源必须包含的访问控制,允许原产地的响应头。如果超过该资源具有控制,你需要这个响应头添加到 * (或者,如果你想有一个更严格的访问控制你的域名)。

In order to be able to access an external resource from javascript. The remote resource MUST include access-control-allow-origin in the response header. If you have control over that resource, you need to add this response header to * (or your domain if you want a more restricted access control).

了解更多关于这个在这里: http://enable-cors.org/

Read more about this here: http://enable-cors.org/

如果你不控制的外部资源。解决方案更加棘手。有人把用YUI做跨域Ajax调用。在这里看到: HTTP:/ /jpvalappil.word$p$pss.com/2010/01/04/cross-domain-ajax-the-yui-way/

If you do not control that external resource. Solutions are more tricky. Some people take use of YUI to do cross-domain ajax calls. See here: http://jpvalappil.wordpress.com/2010/01/04/cross-domain-ajax-the-yui-way/.

如果你正在写一个镀铬的扩展,该API允许您将权限授予您的扩展,从JS访问其他域中的资源。

If you are writing a chrome-extension, the API allows you to grant permissions to your extension to access resources of other domains from js.

这篇关于jQuery的Ajax和的getJSON请求创下的访问控制,允许原产地问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆