我想在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来提交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.

其他回答

使用现代JavaScript!

我建议你研究一下fetch。它是ES5的对等版本,使用Promises。它可读性更强,也更容易定制。

Const url = "http://example.com"; fetch (url, { 方法:"POST", body: new FormData(document.getElementById("inputform")), //——或—— // body: JSON.stringify({ // user: document.getElementById('user').value, / /…… / /}) })( Response => Response .text() // .json(),等等 //与function(response)相同{return response.text();} ) ( HTML => console.log(HTML) );

在Node.js中,你需要使用以下方法导入fetch:

const fetch = require("node-fetch");

如果你想同步使用它(不工作在顶级范围):

const json = await fetch(url, optionalOptions)
  .then(response => response.json()) // .text(), etc.
  .catch((e) => {});

更多信息:

Mozilla的文档

我可以使用吗(2020年11月96%)

大卫·沃尔什教程

下面是一个完整的应用程序json解决方案:

// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">

// return stops normal action and runs login()
<button onclick="return login()">Submit</button>

<script>
    function login() {
        // Form fields, see IDs above
        const params = {
            email: document.querySelector('#loginEmail').value,
            password: document.querySelector('#loginPassword').value
        }

        const http = new XMLHttpRequest()
        http.open('POST', '/login')
        http.setRequestHeader('Content-type', 'application/json')
        http.send(JSON.stringify(params)) // Make sure to stringify
        http.onload = function() {
            // Do whatever with response
            alert(http.responseText)
        }
    }
</script>

确保你的后端API可以解析JSON。

例如,在Express JS中:

import bodyParser from 'body-parser'
app.use(bodyParser.json())

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

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

短而现代

您可以使用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>

下面的代码演示了如何做到这一点。

var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

如果你有/创建一个对象,你可以用下面的代码把它转换成参数,即:

var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;

// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
 urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}