我想在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编写等效内容?
这帮助我,因为我想只使用xmlHttpRequest和post对象作为表单数据:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
使用现代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())
下面的代码演示了如何做到这一点。
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]));
}
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);