【问题标题】:XMLHttpRequest doesn't get responseTextXMLHttpRequest 没有得到 responseText
【发布时间】:2014-04-11 21:19:30
【问题描述】:
我正在从 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 仍然为空?
【问题讨论】:
标签:
javascript
ajax
console
xmlhttprequest
【解决方案1】:
发布的 URL 没有 CORS 标头,但它支持 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);
FIDDLE
【解决方案2】:
确实有效。试试这个 sn-p:
xhr = new XMLHttpRequest();
xhr.open("GET","http://loc.gov/pictures/search/?q=a&fo=json&callback=JSON_CALLBACK",false);
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200)
console.log(xhr.responseText);
};
xhr.send(null);
问题在于您将函数应用于第一个更改。它实际上应该只应用于 XMLHttpRequest 对象的四个状态改变事件
【解决方案3】:
您提供的网址does not work cross-domain。服务器不允许跨域请求。
我使用的版本是返回 JSON 的 JSON 版本。您提供的链接是 JSONP,它不是 AJAX,您必须使用 <script> 来加载它。
顺便说一句,您的代码中缺少 xhr.send(),并且您的 xhr 永远不会发送。