我想在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编写等效内容?
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
或者如果你可以指望浏览器的支持,你可以使用FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
最小限度地使用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 xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
或者如果你可以指望浏览器的支持,你可以使用FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
使用现代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%)
大卫·沃尔什教程
有一些重复的作品涉及到这一点,但没有人真正阐述它。我将借用公认答案的例子来说明
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