我正在尝试使用 jquery ajax 将 formData 发送到服务器... 这是我的 html 文件:
<form id="my_form">
<div>
<p>first name :</p>
<input type="text" name="first_name" value="Bill">
</div>
<div>
<p>second name :</p>
<input type="text" name="second_name" value="Gates">
</div>
<div>
<p>should not send to the server :</p>
<input type="text" value="haha">
</div>
</form>
第一个和第二个输入具有“名称”属性,而最后一个没有,因为我不想将此值发送到服务器。以下是我的 JS 文件:
var formData = new FormData($('#my_form')[0]);
$.ajax({
method : 'POST',
url :'/api/requestUrl',
data : formData,
contentType: false,
processData: false,
success : function() {
...
}
},
});
我的问题来了,当我在IE11中运行时,Request Payload如下图Request Payload in IE , 服务器说它是一个错误的内容体,所以请求失败:
如果我在 Chrome 中运行它,它运行良好,请求负载是: Request Payload in Chrome 我知道如果我从 Dom 中删除最后一个没有“名称”属性的输入,它甚至可以在 IE 中工作,那么,如果我保留最后一个输入,是否有办法让它在 IE 中工作?非常感谢...
最佳答案
据我所知,这确实是一个 IE 错误。一种快速解决方法是在创建 FormData
对象之前禁用未命名的输入。
var $form = $("#my_form");
// Disable "input" elements (input, select, textarea) that do not have
// a name attribute and were not disabled beforehand, saving a reference to them
var $unnamedInputs = $form.find(":input:not([name]):not(:disabled)").prop('disabled', true);
var formData = new FormData($form[0]);
// Re-enable the inputs that we had just disabled
$unnamedInputs.prop('disabled', false);
关于jquery - 防止IE中的 "new FormData()"包含没有name属性的input元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825270/