使用 JsonP 的 JavaScript XMLHttpRequest [英] JavaScript XMLHttpRequest using JsonP

查看:32
本文介绍了使用 JsonP 的 JavaScript XMLHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向其他域发送请求参数

I want to send request parameters to other domain

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

I already know that Cross Scripting needs JsonP and I have used JsonP with Jquery ajax

但我不知道如何使用 XMLHttpRequest 进行交叉脚本

but i do not figure out how to do Cross Scripting as using XMLHttpRequest

以下代码是我的基本 XMLHttpRequest 代码.

following code my basic XMLHttpRequest code.

我想我需要更改 xhr.setRequestHeader() 并且我必须添加解析代码

i guess i need to chage xhr.setRequestHeader() and i have to add parsing code

请给我任何想法

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 does not use XMLHttpRequests.

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

The reason JSONP is used is to overcome cross-origin restrictions of XHRs.

相反,数据是通过脚本检索的.

Instead, the data is retrieved via a script.

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.

In interest of simplicity, this does not include error handling if the request fails. Use script.onerror if you need that.

这篇关于使用 JsonP 的 JavaScript XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆