我正在通过 XMLHttpRequest
发送 POST 请求,并将数据输入到 HTML 表单中。不受 JavaScript 干扰的表单将提交编码为 application/x-www-form-urlencoded
的数据。
使用 XMLHttpRequest,我想通过 FormData
API 发送数据,但该 API 不起作用,因为它将数据视为编码为 multipart/form-data
。因此,我需要将数据作为查询字符串写入 XMLHttpRequest
的发送方法中,并正确转义。
addEntryForm.addEventListener('submit', function(event) {
// Gather form data
var formData = new FormData(this);
// Array to store the stringified and encoded key-value-pairs.
var parameters = []
for (var pair of formData.entries()) {
parameters.push(
encodeURIComponent(pair[0]) + '=' +
encodeURIComponent(pair[1])
);
}
var httpRequest = new XMLHttpRequest();
httpRequest.open(form.method, form.action);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
console.log('Successfully submitted the request');
} else {
console.log('Error while submitting the request');
}
}
};
httpRequest.send(parameters.join('&'));
// Prevent submitting the form via regular request
event.preventDefault();
});
现在这整件事与 for ... of
循环等似乎有点令人费解。有没有更简单的方法将 FormData
转换为查询字符串?或者我可以以某种方式发送具有不同编码的 FormData 吗?
最佳答案
你可以使用 URLSearchParams
const queryString = new URLSearchParams(new FormData(myForm)).toString()
关于javascript - 将 FormData 转换为查询字符串的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980645/