我正在尝试使用 JavaScript 访问维基百科CORS http://en.wikipedia.org/wiki/Cross-origin_resource_sharing%20%29.
据我所知,维基百科应该支持CORS:http://www.mediawiki.org/wiki/API:Cross-site_requests http://www.mediawiki.org/wiki/API:Cross-site_requests
我尝试了以下脚本:创建 XMLHttpRequest+credential/XDomainRequest,添加一些 HTTP 标头(“Access-Control-Allow-Credentials”等)并发送查询。
http://jsfiddle.net/lindenb/Vr7RS/ http://jsfiddle.net/lindenb/Vr7RS/
var WikipediaCORS=
{
setMessage:function(msg)
{
var span=document.getElementById("id1");
span.appendChild(document.createTextNode(msg));
},
// Create the XHR object.
createCORSRequest:function(url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
xhr.open("GET", url, true);
}
else if (typeof XDomainRequest != "undefined")
{
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
return null;
}
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
return xhr;
},
init:function()
{
var _this = this;
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=Javascript&format=json';
var xhr = this.createCORSRequest(url);
if (!xhr)
{
this.setMessage('CORS not supported');
return;
}
xhr.onload = function()
{
_this.setMessage(xhr.responseText);
};
xhr.onerror = function()
{
_this.setMessage('Woops, there was an error making the request.');
};
xhr.send();
}
};
但我的脚本失败(调用“xhr.onerror”)。我该如何修复它?
我在工作时遇到了同样的问题免费代码训练营 https://en.wikipedia.org/wiki/FreeCodeCamp项目和解决方案是如此简单,这让我笑了,因为我花了几个小时寻找它。在您的 jQuery URL 中包含以下参数。
&origin=*
工作代码笔 http://codepen.io/luckyguy73/full/GqPzZO/
$.getJSON(
'https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search' +
'&origin=*' + // <-- this is the magic ingredient!
'&gsrsearch='q, function(data){ /* ... */ }
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)