javascript 如何在纯js上写JSONP Ajax请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23702229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write JSONP Ajax request on pure js?
提问by user2231356
$.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post'
,success:function (data) {
console.log('ok');
},
error:function () {
console.log('error');
}
});
How do I write the same functionality in pure JS?
如何在纯 JS 中编写相同的功能?
回答by desu
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", 'http://forexplay.net/ajax/quotes.php');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
console.log('Response: ' + xmlhttp.responseText );
}else{
console.log('Error: ' + xmlhttp.statusText )
}
}
}
xmlhttp.send(data);
I'm always forgetting about capital and small letters in XMLHttpRequest
我总是忘记 XMLHttpRequest 中的大写和小写字母
回答by Kevin B
In this particular case, you aren't making an ajax call at all, instead you're making a JSONP request. Luckily, these are incredibly easy to replicate and work in all browsers.
在这种特殊情况下,您根本没有进行 ajax 调用,而是进行了 JSONP 请求。幸运的是,这些非常容易复制并在所有浏览器中工作。
var s = document.createElement("script"),
callback = "jsonpCallback_" + new Date().getTime(),
url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
// it worked!
console.log(data);
};
s.src = url;
document.body.appendChild(s);