我正在通过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标头,但确实支持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

09-30 16:27
查看更多