我正在从 Chrome 控制台执行以下操作:(这可能是我的问题的原因吗?)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
console.log("response:",this.responseText);
}
xhr.open('GET', 'http://loc.gov/pictures/search/?q=a&fo=json&callback=JSON_CALLBACK');
该网址有效并且可以跨域。为什么xhr.responseText
仍然为空?
最佳答案
发布的 URL 没有 CORS header ,但支持 JSONP。
另一方面,JSONP 不是 ajax,jQuery 只是巧妙地将其包装起来,但在纯 JavaScript 中,您必须使用脚本标记来获取 JSONP 数据
function JSON_CALLBACK(data) { // define callback function
console.log(data);
}
// then create and insert the script tag, once loaded the callback will be called
var script = document.createElement('script');
script.src = 'http://loc.gov/pictures/search/?q=a&fo=json&callback=JSON_CALLBACK';
document.body.appendChild(script);
关于javascript - XMLHttpRequest 未获取responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022771/