如何在纯js上编写JSONP Ajax请求?

use*_*356 5 javascript ajax jsonp

$.ajax( { url : '', data: {}, dataType:'jsonp',  jsonpCallback: 'callbackName', type: 'post'
        ,success:function (data) {
        console.log('ok');
        },
        error:function () {
        console.log('error');
        }
        });
Run Code Online (Sandbox Code Playgroud)

如何在纯JS中编写相同的功能?

小智 9

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);
Run Code Online (Sandbox Code Playgroud)

我总是忘记XMLHttpRequest中的大写和小写字母

  • xmlhttp.status == 2 xmlhttp.responseText (2认同)

use*_*654 6

在这种特殊情况下,您根本没有进行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);
Run Code Online (Sandbox Code Playgroud)