Javascript 将参数传递给 XMLHttpRequest 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12676698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Parameters To XMLHttpRequest Object
提问by Nick LaMarca
How can I pass parameters to the XMLHttpRequest Object?
如何将参数传递给 XMLHttpRequest 对象?
function setGUID(aGUID) {
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/SetAGUID" , false);
xhReq.send(null);
var serverResponse = JSON.parse(xhReq.responseText);
alert(serverResponse);
return serverResponse;
}
I need to use javascript instead of jquery, in jquery I got it to work with this code, but cant seem to figure it out the straight javascript way..
我需要使用 javascript 而不是 jquery,在 jquery 中我让它与这段代码一起工作,但似乎无法弄清楚直接的 javascript 方式..
function setGUID(aGUID) {
var applicationData = null;
$.ajax({
type: "POST",
url: "ClientService.svc/REST/SetAGUID",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ aGUID: aGUID }),
dataType: "json",
async: false,
success: function (msg) {
applicationData = msg;
},
error: function (xhr, status, error) { ); }
});
return applicationData;
}
回答by lolol
There's a lot of tutorials about "xmlhttprequest post" on the internet. I just copy one of then:
网上有很多关于“xmlhttprequest post”的教程。我只是复制其中之一:
Take a look:
看一看:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
https://www.google.com/search?q=xmlhttprequest+post
https://www.google.com/search?q=xmlhttprequest+post
var http = new XMLHttpRequest();
var url = "url";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
回答by mohamad khaled
Just remove these two lines (which are not allowed to set these headers):
只需删除这两行(不允许设置这些标题):
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
xmlHttp.setRequestHeader("Connection", "close");