交叉原始请求被阻止 [英] Cross origin request blocked

查看:105
本文介绍了交叉原始请求被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从其他网站检索json数据,所以我尝试做一个简单的跨域请求。我在Wamp上运行了这个index.php文件:

I want to retrieve json data from an other website so I tried to do a simple crossdomain request. I ran this index.php file on Wamp :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" manifest="manifest.appcache">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MySite</title>
<script type="text/javascript">
    function getXDomainRequest() {
        var xdr = null;

        if (window.XDomainRequest) {
            xdr = new XDomainRequest();
        } else if (window.XMLHttpRequest) {
            xdr = new XMLHttpRequest({mozSystem: true});
        } else {
            alert("Your browser does not support AJAX");
        }

        return xdr;
    }
    function sendData() {
        var xdr = getXDomainRequest();
        xdr.onload = function() {
            alert(xdr.responseText);
        }

        xdr.open("GET", "http://example.com");
        xdr.send();
    }
</script>
</head>
<body>
<p>
        <input type="button" onclick="sendData();" value="Retrieve" />
</p>
</body>
</html>

但是我收到一条错误消息,说交叉来源请求已被阻止。我是js的新手,这是我第一次尝试在js中使用Web API,所以我可能完全错过了这里的东西......

But I get an error saying that cross origin request has been blocked. I'm pretty new to js and this is the first time I try to use a web API in js so I might have completly missed something here...

谢谢很多。

推荐答案

Javascript请求在某些情况下只能是跨域的。以下是一些技巧和解决方法的摘要。

Javascript requests can only be cross-domain under certain circumstance. Below is a summary of a few techniques and work-arounds.


  1. 如果源有JSONP可用,则可以规避交叉域名限制。 http://www.sitepoint.com/jsonp-examples/

不太可能,但如果源具有源策略,则可以执行跨域请求。看到你收到错误,我怀疑来源有这个政策。如果我记得,所有浏览器都不支持...

Unlikely, but if the source has a origin policy, than you could do the cross domain request. Seeing as you are getting the error, I doubt the source has this policy. If I recall, this is not supported by all browsers...

如果我记得,有一些iFrame方法(我称之为hacks)来运输数据。最好不是最佳。

If I recall, there are some iFrame methods (I would call them hacks) to transport the data. Not optimal at best.

如果所有其他方法都失败了,您可以使用PHP缓存JSON文件并将其存储在您的服务器上。不再是跨域。

If all else fails, you can cache the JSON file with PHP and store it on your server. No longer is it cross domain.

更多细节可以在绕过同源策略的方法

如果你试图从公共API中提取它,而不是它们很可能有JSONP可用。如果他们不这样做,他们可能不希望你每次都提取数据(他们不想占用带宽费用),而是希望你根据需要用PHP缓存它。

If you are attempting to pull it from a public API, than it is very likely that they have JSONP available. If they do not, it is likely that they don't want you to pull the data every time (they don't want to foot the bandwidth bill), but rather would prefer you cache it with PHP as necessary.

这篇关于交叉原始请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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