我正在尝试从网页上接收XML和JSON文件,但是却收到错误消息:
从原点'null'对'http://cis.csuohio.edu/~sschung/CIS408/OnebusinessDataFormat_yelp.json'处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin'标头出现在请求的资源上。
我尝试为xobj.setRequestHeader('Access-Control-Allow-Origin','*');设置响应标头,但这仍然无法解决问题。
这是我的请求代码:
XML请求:
function loadXML(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/xml");
xobj.open('GET', 'http://cis.csuohio.edu/~sschung/CIS408/restaurant_menu.xml', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.setRequestHeader('Access-Control-Allow-Origin','*');
xobj.send(null);
}
JSON请求:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'http://cis.csuohio.edu/~sschung/CIS408/OnebusinessDataFormat_yelp.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.setRequestHeader('Access-Control-Allow-Origin','*');
xobj.send(null);
}
我希望能够导入XML和JSON文件。服务器有问题吗?我是Web编程的新手,但我的理解是服务器将必须允许跨域请求,是吗?