繁体   English   中英

使用JsonP的JavaScript XMLHttpRequest

[英]JavaScript XMLHttpRequest using 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);
        }
    }   
}

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);
});

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

我知道你已经得到了答案但是如果这里的其他人想要一个使用promises的例子就是这个。

function jsonp(url) {
    return new Promise(function(resolve, reject) {
        let script = document.createElement('script')
        const name = "_jsonp_" + Math.round(100000 * Math.random());
        //url formatting
        if (url.match(/\?/)) url += "&callback="+name
        else url += "?callback="+name
        script.src = url;

        window[name] = function(data) {
            resolve(data);
            document.body.removeChild(script);
            delete window[name];
        }
        document.body.appendChild(script);
    });
}
var data = jsonp("https://www.google.com");
data.then((res) => {
    console.log(res);
});
function JsonpHttpRequest(url, callback) {
    var e = document.createElement('script');
    e.src = url;
    document.body.appendChild(script); // fyi remove this element later /assign temp class ..then .remove it later
    //insetead of this you may also create function with  callback value and  use it instead
    window[callback] = (data) => {
        console.log(data);  // heres you data
    }
}
// heres how to use
function HowTouse(params) {
    JsonpHttpRequest("http://localhost:50702/api/values/Getm?num=19&callback=www", "www")
}

对于谷歌api我被迫添加callbackv=1.0参数到网址。 没有v = 1.0参数我得到CORB错误(对于我的版本和其他答案代码 - 但是jQuery $.ajax with dataType: "jsonp"添加此参数 - 所以我也添加它并开始工作)

跨源读取阻止(CORB)阻止跨源响应https://ajax.googleapis.com/ajax/services/feed/load?callback=jsonp1555427800677,MIME类型为text / javascript。 有关详细信息,请参阅https://www.chromestatus.com/feature/5629709824032768

以下是我的解决方案的承诺版本

 function jsonp(url) { return new Promise(function(resolve, reject) { var s = document.createElement('script'); var f="jsonp"+(+new Date()), b=document.body; window[f] = d=>{ delete window[f]; b.removeChild(s); resolve(d); }; s.src=`${url}${url.includes('?')?'&':'?'}callback=${f}&v=1.0`; b.appendChild(s); }) } async function send() { let r = await jsonp("http://ajax.googleapis.com/ajax/services/feed/load"); console.log(r); } 
 <button onclick="send()">Send JSONP</button> 

您无法使用XMLHttpRequest执行Cross Scripting。如果您想要使用Jquery跨域,则必须创建一个新的脚本节点并设置它的src属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM