Home > Article > Web Front-end > Ajax serialize() form to serialize files to upload
This article mainly introduces the ajax information related to uploading files through the serialization method of the Ajax serialize() form. Friends who are interested in ajax can refer to
Submitted through the traditional form form Method to upload files
<form id="uploadForm" action="" method="post" enctype="multipart/form-data"> <p>上传文件:<input type ="file" name="file"/></p> <input type="submit" value="上传"/> </form>
However, traditional form form submission will cause the page to refresh, but in some cases, we do not We hope that the page will be refreshed. In this case, we will use Ajax to make the request.
Use serialize() to serialize and submit the form
$.ajax({ url: "", type: "POST", data: $('#uploadForm').serialize(), success: function(data) { }, error: function(data) { } });
As above, The form can be serialized through $('#uploadForm').serialize(), thereby passing all parameters in the form to the server.
However, in the above method, only general parameters can be passed, and the file stream of the uploaded file cannot be serialized and passed. However, now mainstream browsers have begun to support an object called FormData. With this object, you can easily upload files using Ajax.
Use FormData to make Ajax requests and upload files
<form id="uploadForm"> <p>上传文件:<input type="file" name="file" /></p> <input type="button" value="上传" onclick="upload()" /> </form> function upload() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: '', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function(data) { }, error: function(data) { } }); }
The above is a small The editor introduces to you the Ajax serialize() form to serialize files for uploading. I hope it will be helpful to you! !
Related recommendations:
Example method of handwritten Ajax to achieve asynchronous refresh
Example to explain the basic knowledge of HTTP messages and ajax
Example analysis of Ajax asynchronous request technology
The above is the detailed content of Ajax serialize() form to serialize files to upload. For more information, please follow other related articles on the PHP Chinese website!