我想在JavaScript中使用XMLHttpRequest发送一些数据。

假设我在HTML中有以下表单:

<form name="inputform" action="somewhere" method="post">
  <input type="hidden" value="person" name="user">
  <input type="hidden" value="password" name="pwd">
  <input type="hidden" value="place" name="organization">
  <input type="hidden" value="key" name="requiredkey">
</form>

如何在JavaScript中使用XMLHttpRequest编写等效内容?


当前回答

短而现代

您可以使用FormData捕获表单输入值并通过fetch发送它们

fetch(form.action, {method:'post', body: new FormData(form)});

function send() { let form = document.forms['inputform']; fetch(form.action, {method:'post', body: new FormData(form)}); } <form name="inputform" action="somewhere" method="post"> <input value="person" name="user"> <input type="hidden" value="password" name="pwd"> <input value="place" name="organization"> <input type="hidden" value="key" name="requiredkey"> </form> <!-- I remove type="hidden" for some inputs above only for show them --><br> Look: chrome console>network and click <button onclick="send()">send</button>

其他回答

尝试使用json对象而不是formdata。下面是为我工作的代码。formdata也不适合我,因此我提出了这个解决方案。

var jdata = new Object();
jdata.level = levelVal; // level is key and levelVal is value
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://MyURL", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(jdata));

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
}

短而现代

您可以使用FormData捕获表单输入值并通过fetch发送它们

fetch(form.action, {method:'post', body: new FormData(form)});

function send() { let form = document.forms['inputform']; fetch(form.action, {method:'post', body: new FormData(form)}); } <form name="inputform" action="somewhere" method="post"> <input value="person" name="user"> <input type="hidden" value="password" name="pwd"> <input value="place" name="organization"> <input type="hidden" value="key" name="requiredkey"> </form> <!-- I remove type="hidden" for some inputs above only for show them --><br> Look: chrome console>network and click <button onclick="send()">send</button>

最小限度地使用FormData来提交AJAX请求

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>
</form>
</body>
</html>

讲话

This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

var util = {
    getAttribute: function (dom, attr) {
        if (dom.getAttribute !== undefined) {
            return dom.getAttribute(attr);
        } else if (dom[attr] !== undefined) {
            return dom[attr];
        } else {
            return null;
        }
    },
    addEvent: function (obj, evtName, func) {
        //Primero revisar attributos si existe o no.
        if (obj.addEventListener) {
            obj.addEventListener(evtName, func, false);

        } else if (obj.attachEvent) {
            obj.attachEvent(evtName, func);
        } else {
            if (this.getAttribute("on" + evtName) !== undefined) {
                obj["on" + evtName] = func;
            } else {
                obj[evtName] = func;
            }

        }

    },
    removeEvent: function (obj, evtName, func) {
        if (obj.removeEventListener) {
            obj.removeEventListener(evtName, func, false);
        } else if (obj.detachEvent) {
            obj.detachEvent(evtName, func);
        } else {
            if (this.getAttribute("on" + evtName) !== undefined) {
                obj["on" + evtName] = null;
            } else {
                obj[evtName] = null;
            }
        }

    },
    getAjaxObject: function () {
        var xhttp = null;
        //XDomainRequest
        if ("XMLHttpRequest" in window) {
            xhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xhttp;
    }

};

//START CODE HERE.

var xhr = util.getAjaxObject();

var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));

if (isUpload) {
    util.addEvent(xhr, "progress", xhrEvt.onProgress());
    util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
    util.addEvent(xhr, "abort", xhrEvt.onAbort);
}

util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);

var xhrEvt = {
    onProgress: function (e) {
        if (e.lengthComputable) {
            //Loaded bytes.
            var cLoaded = e.loaded;
        }
    },
    onLoadStart: function () {
    },
    onAbort: function () {
    },
    onReadyState: function () {
        var state = xhr.readyState;
        var httpStatus = xhr.status;

        if (state === 4 && httpStatus === 200) {
            //Completed success.
            var data = xhr.responseText;
        }

    }
};
//CONTINUE YOUR CODE HERE.
xhr.open('POST', 'mypage.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');


if ('FormData' in window) {
    var formData = new FormData();
    formData.append("user", "aaaaa");
    formData.append("pass", "bbbbb");

    xhr.send(formData);

} else {

    xhr.send("?user=aaaaa&pass=bbbbb");
}

有一些重复的作品涉及到这一点,但没有人真正阐述它。我将借用公认答案的例子来说明

http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');

为了说明,我过度简化了这一点(我使用http.onload(function(){})而不是那个答案的旧方法)。如果你按原样使用,你会发现你的服务器可能会将POST正文解释为字符串,而不是实际的key=value参数(即PHP不会显示任何$_POST变量)。你必须在http.send()之前传递表单头文件来获取它。

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

如果您使用的是JSON而不是url编码的数据,则应该传递application/ JSON