使用JsonP的JavaScript XMLHttpRequest

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

我已经知道交叉脚本需要JsonP,而且我已经使用JsonP和Jquery ajax

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

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

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

请给我任何想法

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

为了简单起见,如果请求失败,这不包括error handling。 如果你需要使用script.onerror

您无法使用XMLHttpRequest进行交叉脚本编写。如果您想通过Jquery进行跨域交换,您必须创build一个新的脚本节点并设置它的src属性。