JQuery asynchronous submission of data files based on FormData

  • 2021-08-10 06:44:04
  • OfStack

Data submission events are common in web, But in most cases we don't want to submit using the form form in html, Because the form form submission interrupts the current browser and goes to another address (even if that address is the current page), And it will waste bandwidth by loading some html repeatedly. We hope to achieve a refresh-free and asynchronous submission effect to give users a better experience. At this time, we should use ajax. ajax can initiate an http request and retrieve the data responded by the server without relying on the form, which is the simplicity of ajax. We use the ajax function encapsulated in JQuery here, which is simpler. Here are a few methods to commit data asynchronously using ajax.

1: $. ajax method in jquery. js

This method relies on the jquery. js plug-in, which is available in many versions and can be downloaded by yourself.

We need to specify 1 parameters in this $. ajax method, such as request address, request type, data to be transmitted, and operation to be performed after successful request, which is briefly described here.


$.ajax({
    url:" Yours url Address ",
    type:'post',
    data:{key:'value'},
    success:function(){
      alert(' Success ') ; 
    }
  })


This is a simple use of the $. ajax method. The parameter data is the data you want to transfer, and data supports Json objects and strings. If data data is in an form form, it is slow to write an json by yourself, so you can use serizlize () method in jquery. This method returns 1 string (each form form is converted to the same format when it is submitted).


$.ajax({
    url:" Yours url Address ",
    type:'post',
    data:$('form').serialize(), // "id=asdasd&s=000&name=1233"
    success:function(){
      alert(' Success ') ; 
    }
  })

So, is the document submitted in the same way?

For file submission, we need to make some special settings for $. ajax and use FormData objects.

<input type="file" name="f" id="f" multiple>


var fd = new FormData();
    fd.append("name", "bill");
    fd.append("photo", $('#f')[0].files[0]);
    fd.append("photo2", $('#f')[0].files[1]);
    $.ajax({
      url: '/webform1.aspx',
      type: 'post',
      processData: false,
      contentType: false,
      data: fd,
      success: function () {
        alert("ok")
      }
    })

We create an fd object and add a key-value pair to it, which can be a file. $('# f') [0] is the element that fetches id = f. As for why [0], this is because jquery objects have an index that defaults to 0 to fetch their Dom elements. $('f') is an jquery object, and [0] is all the properties and methods that Dom elements can use with dom. Then use files to check out the file. Here I used files [0] and files [1], which is multiple can upload multiple files. I uploaded two here.

Then the server can receive the file, and the receiving method like Form 1.

Of course, one form can be directly converted into one FormData object, so that we can avoid putting the required content one append into FormData.


var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
 url: "stash.php",
 type: "POST",
 data: fd,
 processData: false, //  Do not process data 
 contentType: false  //  Do not set the content type 
});

When adding append, if key of formdata already exists, it cannot be added repeatedly, and this append operation will be ignored, which is quite unfavorable for using the form to take out values frequently. Therefore, it is recommended to use set method to add new key-value values. set means modifying an existing key-value pair, and creating one if it does not exist. I.e.

fd.set("CustomField", "This is some extra data");
$. ajax is an active event, and we want it to be executed when the user clicks a button. Here, we can put the $. ajax function in the click event of 1 button, or we can use the following method.


$('form').submit(function{
  //  Your own code, 1 It is generally data legality verification 
$.ajax({ 
     
   });
   return false;
})

The submit function can be executed when the form is submitted, and we can use it as a trigger event to execute the $. ajax function, and then use return false to prevent the submission of this form in advance.

Note: Some articles talk about the compatibility of FormData, and FormData has been proposed for a long time. And if you want to use ajax in jquery to transfer files, you have to use it because the following two methods also use FormData. Of course, the native ajax has a direct file transfer method, interested people can look at it.


Related articles: