【发布时间】:2017-08-16 06:41:37
【问题描述】:
我正在通过XMLHttpRequest 发送一个 POST 请求,并将数据输入到 HTML 表单中。不受 JavaScript 干扰的表单会提交编码为application/x-www-form-urlencoded 的数据。
使用 XMLHttpRequest,我想通过 FormData 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 吗?
【问题讨论】:
-
@Andreas 这是缩短代码的一种方法,因此请随意添加它作为答案。
标签: javascript xmlhttprequest form-data