Javascript Http请求到另一个域

时间:2014-05-14 09:28:31

标签: javascript xmlhttprequest cross-domain

我想从另一个网域的网页上获取数据但我收到此错误

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];
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果请求的网址是PHP文件,则应在页面顶部添加此标题:

header('Access-Control-Allow-Origin: *');  

您可以输入您要求的域名,而不是通配符。


根据你的回复,你应该在.htaccess中设置如下:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

我是从this source

得到的