Ajax - FromData objects

The role of the object FormData

  1. Analog HTML form is equivalent to mapping the HTML form to the form object, the data form object automatically spliced ​​into the format of request parameters.

  2. Asynchronous upload binary files

Use FormData object

  1. Ready HTML form
 <form id="form">
     <input type="text" name="username" />
     <input type="password" name="password" />
     <input type="button"/>
</form>
  1. The HTML form objects into formData
var form = document.getElementById('form'); 
var formData = new FormData(form);
  1. Submit the form objects
xhr.send(formData);

note:

  1. Formdata get request object can not be used, because the object needs to be passed to the send process, the get request and the request parameters embodiment only on the back of the request address.

  2. bodyParser node server module can not be resolved formData form data objects, we need to use the formidable module for resolution.

Examples of the method object FormData

  1. Acquiring attribute values ​​form object
formData.get('key');

key: name value as a form of

  1. Value of the form object properties
formData.set('key', 'value');
  1. Value delete form object properties
formData.delete('key');
  1. Attribute value is added to the form object
formData.append('key', 'value');

Note: The difference between the set method and append method is that in the case of property name already exists, set the value of the key will overwrite the existing name, append the two values ​​will be retained.

FormData can create an empty object, then use the append method added value

FormData binary file upload

<input type="file" id="file"/>
 var file = document.getElementById('file')
// 当用户选择文件的时候
 file.onchange = function () {
     // 创建空表单对象
     var formData = new FormData();
     // 将用户选择的二进制文件追加到表单对象中
     formData.append('attrName', this.files[0]);
     // 配置ajax对象,请求方式必须为post
     xhr.open('post', 'www.example.com');
     xhr.send(formData);
 }

FormData show file upload progress

// 当用户选择文件的时候
 file.onchange = function () {
     // 文件上传过程中持续触发onprogress事件
     xhr.upload.onprogress = function (ev) {
         // 当前上传文件大小/文件总大小 再将结果转换为百分数
         // 将结果赋值给进度条的宽度属性 
         bar.style.width = (ev.loaded / ev.total) * 100 + '%';
     }
 }

FormData file upload pictures instantly preview

We will upload pictures to the server after the server usually the address of the picture as a response data to the client, the client can get the address of the picture from the response data, and then again the picture displayed on the page.

 xhr.onload = function () {
     var result = JSON.parse(xhr.responseText);
     var img = document.createElement('img');
     img.src = result.src;
     img.onload = function () {
         document.body.appendChild(this);
     }
 }

Guess you like

Origin www.cnblogs.com/royal6/p/12589234.html