我正在尝试使用 JavaScript 和CORS访问维基百科。
据我所知,维基百科应该支持 CORS:http : //www.mediawiki.org/wiki/API :Cross-site_requests
我尝试了以下脚本:创建一个 XMLHttpRequest+credential/XDomainRequest,添加一些 HTTP 标头(“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')。我该如何解决?