我想在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>
我也遇到过类似的问题,使用相同的帖子和这个链接,我已经解决了我的问题。
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
此链接已完成信息。
下面是一个完整的应用程序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
只是为了让专题读者发现这个问题。我发现,只要你有一个给定的路径,接受的答案就可以工作,但如果你让它为空,它将在IE中失败。以下是我想到的:
function post(path, data, callback) {
"use strict";
var request = new XMLHttpRequest();
if (path === "") {
path = "/";
}
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function (d) {
callback(d.currentTarget.response);
};
request.send(serialize(data));
}
你可以这样写:
post("", {orem: ipsum, name: binny}, function (response) {
console.log(respone);
})
使用现代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%)
大卫·沃尔什教程