简体   繁体   English

将参数传递给 XMLHttpRequest 对象

[英]Pass Parameters To XMLHttpRequest Object

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;

}

There's a lot of tutorials about "xmlhttprequest post" on the internet.网上有很多关于“xmlhttprequest post”的教程。 I just copy one of then:我只是复制其中之一:

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

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

This way works for me.这种方式对我有用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM