How to use Ajax to upload data and files at the same time?
P粉012875927
2023-08-20 14:33:32
<p>I'm using jQuery and Ajax to submit data and files, but I'm not sure how to send both data and files in one form? </p>
<p>I currently use both methods in almost the same way, but the way of collecting the data into an array is different, data uses <code>.serialize();</code> and files uses <code> ;= new FormData($(this)[0]);</code></p>
<p>Is it possible to combine these two methods to upload files and data in one form via Ajax? </p>
<p><strong>Data jQuery, Ajax and html</strong></p>
<pre class="brush:php;toolbar:false;">$("form#data").submit(function(){
var formData = $(this).serialize();
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="data" method="post">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<button>Submit</button>
</form></pre>
<p><strong>Documentation jQuery, Ajax and html</strong></p>
<pre class="brush:php;toolbar:false;">$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="files" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form></pre>
<p>How can I combine the above so that I can send data and files in one form via Ajax? </p>
<p>My goal is to be able to send all these forms together via Ajax, is this possible?</p>
<pre class="brush:php;toolbar:false;"><form id="datafiles" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>提交</button>
</form></pre>
<p><br /></p>
Another option is to use an iframe and set the form's target to it.
You can try this (it uses jQuery):
It works in all browsers, you don't need to serialize or prepare the data. One drawback is that you can't monitor progress.
Also, at least for Chrome, the request does not appear under the "xhr" tab of the developer tools, but under "doc".
The problem I had was using the wrong jQuery identifier.
You can use a formUse ajax to upload data and files.
PHP HTML
jQuery Ajax
Simplified version