我想从其他网站检索json数据,所以我试图做一个简单的跨域请求。我在Wamp上运行了这个index.php文件:跨域请求被阻止
<!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,所以我可能完全错过了这里的东西......
非常感谢。
'XMLHttpRequest'不适用于跨域请求。请参阅[JSONP](http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about)。 –
好的,但XDomainRequest是否正确? 我在查询不支持JSONP的[Steam API](https://developer.valvesoftware.com/wiki/Steam_Web_API#GetGlobalAchievementPercentagesForApp_.28v0001.29)。 – deKajoo
请勿使用浏览器提出此请求,否则您的api密钥将免费提供给任何人(无论谁?)使用您的应用程序。 –