【发布时间】:2014-05-14 17:43:47
【问题描述】:
我想从另一个域的网页中获取数据,但出现此错误
No 'access-control-allow-origin' header is present on the requested resource
我已经尝试过此博客 http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ 中的 CORS 示例,但我仍然遇到相同的错误。
当我在应用程序中运行页面时,我设法获取了页面的内容(我在 Titanium 应用程序中所做的事情,现在在运行在浏览器中的 PhoneGap 中工作)
这是我的脚本
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function insertText () {
var artist = [];
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var xhr = createCORSRequest('GET', "http://www.rockwerchter.be/en/line-up");
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.open("GET", "http://www.rockwerchter.be/en/line-up");
xhr.send();
xhr.onload = function(){
text = request.responseText;
var regex = new RegExp(".*box-title box-title-h3 mb-05.*", "g");
artist = text.match(regex);
var data = [];
for (var i=0; i<artist.length; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
artist[i]= artist[i].replace("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<h2 class=\"box-title box-title-h3 mb-05\">", "");
artist[i]= artist[i].replace("</h2>","");
tr.innerHTML=artist[i];
}
}
}
【问题讨论】:
-
也就是说这个网站只是不支持CORS?
-
我仍然希望我只是错过了一些东西。我需要添加一些标题吗?
-
但是当我在应用程序中运行它时设法获取页面的内容(我在 Titanium 应用程序中所做的事情,现在在浏览器中运行的 PhoneGap 中工作)
-
不行,你请求的站点需要添加header!
标签: javascript xmlhttprequest cross-domain