15

如何将参数传递给 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;
}

我需要使用 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;

}
4

3 回答 3

24

网上有很多关于“xmlhttprequest post”的教程。我只是复制其中一个:

看一看:

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

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);
于 2012-10-01T15:55:55.080 回答
0

只需删除这两行(不允许设置这些标题):

http.setRequestHeader("Content-type", "application/json; charset=utf-8");
xmlHttp.setRequestHeader("Connection", "close");
于 2020-03-03T22:31:41.653 回答
0

这种方式对我有用。

var data = new FormData();
data.append('parameter_1', 'value parameter 1');
data.append('parameter_2', 'value parameter 2');
...

var xhr = new XMLHttpRequest();
xhr.open('POST', 'URL', true);
xhr.onload = function () {
    console.log(this.responseText);
};
xhr.send(data);
于 2020-08-13T21:15:25.623 回答