FormData in Ajax: Complete Guide

When using Ajax, you can serialize form data using the FormData object and send it to the server in key/value pairs.

Here is the general process of using the FormData object:

  1. There are two ways to create a FormData object: you can either instantiate a new FormData object directly, or create one by passing a form element.
// 创建一个新的FormData对象
var formData = new FormData();

// 通过form元素创建FormData对象
var form = document.getElementById('myForm');
var formData = new FormData(form);
  1. Add data to FormData object: You can use the append() method to add key/value pairs to a FormData object.
formData.append('name', 'John Doe');
formData.append('email', 'johndoe@example.com');
  1. Send the FormData object to the server: You can pass the FormData object as the data parameter to the send() method of an Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'example.php', true);
xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
        console.log(xhr.responseText);
    } else {
        console.error('Request failed: ' + xhr.status);
    }
};
xhr.send(formData);

By following the steps above, you can use the FormData object to serialize form data and send it to the server.

bannerAds