我正在尝试使用 JavaScript 和 CORS 访问维基百科.
据我所知,维基百科应该支持CORS:http://www.mediawiki.org/wiki/API:Cross-site_requests
我尝试了以下脚本:创建 XMLHttpRequest+credential/XDomainRequest,添加一些 HTTP header (“Access-Control-Allow-Credentials”等)并发送查询。
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”)。我该如何修复它?
最佳答案
我在处理 freeCodeCamp 时遇到了同样的问题项目和解决方案是如此简单,这让我笑了,因为我花了几个小时寻找它。在您的 jQuery URL 中包含以下参数。
&origin=*
$.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){ /* ... */ }
);
关于javascript - 维基百科 API + 跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952045/