使用JSONP的JavaScript XMLHtt prequest [英] JavaScript XMLHttpRequest using JsonP
问题描述
我要发送的请求参数到其他域
我已经知道了跨脚本需要JSONP,我已经使用JSONP与jQuery阿贾克斯
但我不知道如何做跨脚本作为使用XMLHtt prequest
以下$ C C我的基本XMLHtt prequest code $。
我想我需要恰克 xhr.setRequestHeader()
和我要补充解析code
请给我任何的想法
VAR XHR;
功能createXMLHtt prequest(){
如果(window.AtiveXObject){
XHR =新的ActiveXObject(Microsoft.XMLHTTP);
}其他{
XHR =新XMLHtt prequest();
}
VAR URL =http://www.helloword.com;
}
功能openRequest(){
createXMLHtt prequest();
xhr.onreadystatechange =的getData;
xhr.open(POST,网址,真实);
xhr.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD');
xhr.send(数据);
}
功能的getData(){
如果(xhr.readyState == 4){
如果(xhr.status == 200){
VAR TXT = xhr.responseText;
警报(TXT);
}
}
}
JSONP不使用XMLHtt prequests。
原因JSONP采用的是克服XHRs的跨域限制。
相反,数据经由脚本检索
功能JSONP(URL,回调){
变种callbackName ='jsonp_callback_'+ Math.round(100000 *的Math.random());
窗口[callbackName] =功能(数据){
删除窗口[callbackName]
document.body.removeChild(脚本);
回调(数据);
};
VAR脚本= document.createElement方法(脚本);
script.src = URL +('?'url.indexOf()> = 0'和;':'?')+'回调='+ callbackName;
document.body.appendChild(脚本);
}
JSONP('http://www.helloword.com',功能(数据){
警报(数据);
});
在简化的兴趣,这不包括错误,如果请求失败处理。使用 script.onerror
如果你需要的。
I want to send request parameters to other domain
I already know that Cross Scripting needs JsonP and I have used JsonP with Jquery ajax
but i do not figure out how to do Cross Scripting as using XMLHttpRequest
following code my basic XMLHttpRequest code.
i guess i need to chage xhr.setRequestHeader()
and i have to add parsing code
please give me any idea
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 does not use XMLHttpRequests.
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);
});
In interest of simplicity, this does not include error handling if the request fails. Use script.onerror
if you need that.
这篇关于使用JSONP的JavaScript XMLHtt prequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!