Function and usage of new FormData() - FormData object

Introduction of js FormData Method

1. Overview

The FormData type is actually defined at the level of XMLHttpRequest 2, which facilitates the serialization of tables and the creation of data in the same format as the form (for XHR transmission, of course).

2. Constructor

There are several ways to create a form Data object instance:

1. Create an empty object instance

var formData = new FormData();

At this point, you can call the append() method to add data

2. Initialize an object instance using an existing form

Suppose the page already has a form

<form id="myForm" action="" method="post">
    <input type="text" name="name">Name
    <input type="password" name="psw">Password
    <input type="submit" value="Submission">

We can use this form element as an initialization parameter to instantiate a formData object

// Get an existing form form on the page
var form = document.getElementById("myForm");
// Initialization with forms
var formData = new FormData(form);
// We can access the fields in the form by name
var name = formData.get("name"); // Get the name
var psw = formData.get("psw"); // Get the password
// Of course, other data can also be added on this basis.

3. Operating methods

First, we need to clarify the form of data stored in formData. A pair of keys / values form a single data. A key is unique, and a key may correspond to multiple values. If form initialization is used, each form field corresponds to a data, their HTML name attribute is the key value, and their value attribute corresponds to the value value value.

3.1 Get Value

We can get(key)/getAll(key) to get the corresponding value.

formData.get("name"); // Get the first value of key as name
formData.get("name"); // Returns an array to get all the values whose key is name

3.2 Adding Data

We can add data by append(key, value), add a new data if the specified key does not exist, and add it to the end of the data if the key exists.

formData.append("k1", "v1");
formData.append("k1", "v2");
formData.append("k1", "v1");

formData.get("k1"); // "v1"
formData.getAll("k1"); // ["v1","v2","v1"]

3.3 Setting Update Data

We can set the modification data by setting (key, value), add a new key if the specified key does not exist, and modify the corresponding value if it exists.

formData.append("k1", "v1");
formData.set("k1", "1");
formData.getAll("k1"); // ["1"]

3.4 Judging whether the data is available

We can use has(key) to determine whether the key value corresponds to it or not.

formData.append("k1", "v1");

formData.has("k1"); // true
formData.has("k2"); // true
formData.has("k3"); // false

3.5 Delete data

Delete data by delete(key)

formData.append("k1", "v1");
formData.append("k1", "v2");
formData.append("k1", "v1");

formData.getAll("k1"); // []

3.6 traversal

We can get an iterator through entries(), and then traverse all the data.

formData.append("k1", "v1");
formData.append("k1", "v2");
formData.append("k2", "v1");

var i = formData.entries();; // {done:false, value:["k1", "v1"]}; // {done:fase, value:["k1", "v2"]}; // {done:fase, value:["k2", "v1"]}; // {done:true, value:undefined}

You can see the rules for returning iterators

  1. Each call to next() returns one piece of data, the order of which is determined by the order in which the data is added.

  2. It returns an object whose done attribute is true, indicating that all data has been traversed, which can also be used as a basis for judgment.

  3. The value attribute of the returned object stores a pair of keys/values in the form of an array, with the array subscript 0 as key and the subscript 1 as value. If a key value corresponds to multiple values, it will become multiple key/value returns.

We can also get only value values through the values() method

formData.append("k1", "v1");
formData.append("k1", "v2");
formData.append("k2", "v1");

var i = formData.entries();; // {done:false, value:"v1"}; // {done:fase, value:"v2"}; // {done:fase, value:"v1"}; // {done:true, value:undefined}

4. Send data

We can send data through xhr

var xhr = new XMLHttpRequest();"post","login");

This way can realize the asynchronous upload of files.


2. Practice of FormData

1. Overview

Use of FormData objects:
1. Use some key-value pairs to simulate a series of form controls: assembling the name and value of all form elements in the form
A queryString
2. Asynchronous upload of binary files.

2. Use

1. The operation methods of FormData objects are all in the prototype, and they have no attributes and methods of their own.

let formData = new FormData()
formData.append('user', 'zhang')
//Get formData. get ('user')//zhang
//Delete formData.delete('user')

2. Send files using FormData objects

<form action="">
	<label for="">
		//Name: <input type= "text" name= "name">
	<label for="">
		//File: <input id= "file" type= "file" name= "file">
	<label for="">
		<input type="button" value="Preservation">
JS Part
var btn = document.querySelector('[type=button]');
btn.onclick = function () {
    // File elements
    var file = document.querySelector('[type=file]');
    // Converting files to binary data through FormData
    var formData = new FormData();
    // Converting files to binary
    *****Note 2******
    formData.append('upload', file.files[0]);
    *****Note 1******
    var xhr = new XMLHttpRequest;'post', 'file.php');
    // Monitor upload progress
    xhr.upload.onprogress = function (ev) {
    // Event object
    // console.log(ev);
        var percent = (ev.loaded / * 100 + '%';
        console.log(percent); = percent;

    xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && xhr.status == 200) {


Note 1: Use jQuery

    url: 'file.php',
    type: 'POST',
    data: formdata,                    // Upload formdata encapsulated data
    dataType: 'JSON',
    cache: false,                      // No caching
    processData: false,                // jQuery does not handle the data sent
    contentType: false,                // jQuery does not set the Content-Type request header
    success:function (data) {           //Successful callback


Note 2: Parameters

The parameter of new FormData is a DOM object, not a jQuery object.

var formData = new FormData($("#file")[0]);

3. jQuery's parametric serialization method serialize()

The table content of the sequence table is a string for Ajax requests.  


Reference documents:

Tags: JQuery Attribute PHP JSON

Posted on Tue, 27 Aug 2019 03:31:54 -0700 by dinsdale