Reputation: 23
I am trying to use jquery ajax to send formData to server... Here is my html file:
<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>
the first and the second input have the 'name' attribute while the last one do not, since I do not want to send this value to the server.The following is my JS file:
var formData = new FormData($('#my_form')[0]);
$.ajax({
method : 'POST',
url :'/api/requestUrl',
data : formData,
contentType: false,
processData: false,
success : function() {
...
}
},
});
Here comes my question,When I run this in IE11, the Request Payload likes the following pictureRequest Payload in IE, and the server says it is a bad content body, so the request failed:
And If I run this in Chrome, it works well,the Request Payload is : Request Payload in Chrome I know that if I remove the last input which does not have the 'name' attribute from the Dom, it will work even in IE, So, is there a way to make it work in IE if I remain the last input? thanks a lot...
Upvotes: 2
Views: 195
Reputation: 70169
As far as I can tell, this is indeed an IE bug. One quick workaround is to disable the unnamed input before creating the FormData
object.
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);
Upvotes: 1
Reputation: 1
You could clone the original form
, remove last input
element or input
element that does not have name
attribute, then set FormData
parameter to cloned form
where last input
would not be included.
var clone = $("#my_form").clone();
clone.find("input:last").remove();
var formData = new FormData(clone[0]);
Upvotes: 0