我想在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编写等效内容?
只是为了让专题读者发现这个问题。我发现,只要你有一个给定的路径,接受的答案就可以工作,但如果你让它为空,它将在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%)
大卫·沃尔什教程
下面的代码演示了如何做到这一点。
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);
只是为了让专题读者发现这个问题。我发现,只要你有一个给定的路径,接受的答案就可以工作,但如果你让它为空,它将在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);
})
这帮助我,因为我想只使用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