使用JsonP的JavaScript XMLHttpRequest

hap*_*ask 27 javascript ajax jsonp

我想将请求参数发送到其他域

我已经知道Cross Scripting需要JsonP,我已经将JsonP与Jquery ajax一起使用了

但我不知道如何使用XMLHttpRequest进行Cross Scripting

下面的代码我的基本XMLHttpRequest代码.

我想我需要chage xhr.setRequestHeader(),我必须添加解析代码

请给我任何想法

var xhr;
function createXMLHttpRequest(){    
    if(window.AtiveXObject){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        xhr = new XMLHttpRequest();
    }   
    var url = "http://www.helloword.com";   
}

function openRequest(){ 
    createXMLHttpRequest();
    xhr.onreadystatechange = getdata;
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type",'application/x-www-form-urlencoded');
    xhr.send(data); 
}

function getdata(){
    if(xhr.readyState==4){
        if(xhr.status==200){
            var txt = xhr.responseText;
            alert(txt);
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*per 67

JSONP不使用XMLHttpRequests.

使用JSONP的原因是为了克服XHR的跨源限制.

而是通过脚本检索数据.

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
}

jsonp('http://www.helloword.com', function(data) {
   alert(data);
});
Run Code Online (Sandbox Code Playgroud)

为简单起见,如果请求失败,则不包括错误处理.script.onerror如果您需要,请使用.