使用JsonP的JavaScript XMLHttpRequest

问题描述 投票:25回答:5

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

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

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

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

我想我需要更改qazxsw poi,我必须添加解析代码

请给我任何想法

xhr.setRequestHeader()
javascript ajax jsonp
5个回答
64
投票

JSONP不使用XMLHttpRequests。

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

而是通过脚本检索数据。

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

为简单起见,如果请求失败,则不包括错误处理。如果需要,请使用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); });


0
投票

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

script.onerror

0
投票
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);
});

-1
投票

对于google api,我被迫将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") } callback参数添加到url。没有v = 1.0参数我得到CORB错误(对于我的版本和其他答案代码 - 但jQuery v=1.0$.ajax添加此参数 - 所以我也添加它并开始工作)

跨源读取阻止(CORB)阻止了具有MIME类型text / javascript的跨源响应dataType: "jsonp"。有关详细信息,请参阅https://ajax.googleapis.com/ajax/services/feed/load?callback=jsonp1555427800677

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

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

-4
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.