An example analysis of the data parameter type of Ajax () in jquery _jquery

Source: Internet
Author: User

This example analyzes the data parameter types of Ajax () in jquery. Share to everyone for your reference, specific as follows:

The previous simple analysis introduces the "Two methods of data transfer in Ajax", the Ajax parameter transfer method has a preliminary understanding, here to further analyze the AJAX data parameter type.

If you have such a form now, it is for adding elements.

<form id= ' addform ' action= ' useradd.action ' type= ' post ' >
  <label for= ' uname ' > Username </label>:< Input type= ' text ' name= ' uname ' id= ' uname ' ><br>
  <label for= ' mobileipt ' > mobile phone number:</label>< Input type= ' text ' name= ' mobileipt ' id= ' mobileipt ' ><br>
  <label for= ' birthday ' > Birthday:</label> <input type= ' text ' name= ' birthday ' ><br>
  <input type= ' button ' value= ' submitted ' onclick= ' AddUser () ' >
</form>

We do not want to add this element using the form Submit method, we would like to use Ajax to submit.

That's how we've done it before:

function AddUser () {
  var user = {
   uname:$ ("#uname"). Val (),
   mobileipt:$ ("#mobileIpt"). Val (),
   birthday:$ ("#birthday"). Val ()
  };
  $.ajax ({
   URL: ' useradd.action ',
   data:user,
   type: ' Post ',
   dataType: ' text ',
   success:function (msg) {
    if (msg== ' 1 ') {
     console.log (' Add success ');
    } else{
     console.log (' Add Failed '}}}
  )
}

There's nothing wrong with that: getting the value of a form element is too much trouble .... There are only three items, many of which are obsolete ....

Until one day, I discovered the Serializearray method of jquery.

The serialized Table element (similar to the '. Serialize () ' method) returns the JSON data structure.

Note that this method returns a JSON object rather than a JSON string. You need to use Plug-ins or Third-party libraries for string manipulation.

The returned JSON object is composed of an array of objects, each of which contains one or two name values for the--name parameter and the value argument (if value is not empty).

Let's try it.

$ (' #addForm '). Serializearray ();
Returns the data structure, which is a JSON array, with each pair like name and value key, representing the name and value
[{' name '] of the form element
 : ' uname ', ' value ': ' '},
 {' name ': ' Mobileipt "," Value ":" "}, 
 {" name ":" Birthday "," Value ":" "}
]

This doesn't seem to work.

We use the Jquery.param () method to deal with:

var arr = $ (' #addForm '). Serializearray ();
$.param (arr);
" Uname=alice&mobileipt=110&birthday=1983-05-12 "

Hey, this fits our needs, though it's not a JSON type, but it can be uploaded as data at least.

Here we can fill out this JSON array directly in the AJAX data, and call $.param () within jquery to handle it.

Let's look at the description of the Jquery.param () method:

return value: Stringjquery.param (Obj,[traditional])

Serializes a group of table cell primes or objects.

Parameters:

Obj,[traditional]

Arrays or jquery objects are serialized according to Name/value, and ordinary objects are serialized according to Key/value.

Traditional: Whether to use the traditional way of shallow serialization.

Demo

$.param ({uanme: ' Vic ', Mobileipt: ' A ', Birthday: ' 2013-11-11 '});
Uanme=vic&mobileipt=110&birthday=2013-11-11 "

Look at the description, it seems to have nothing to do with us ah, we change a JSON array to see

$.param ([{uanme: ' Vic '},{mobileipt: ' [2013-11-11 ']},{birthday: ']);
" Undefined=&undefined=&undefined= "

This conversion is unsuccessful, why is the data in our form successfully converted to URL parameters? Let's look at the jquery source.

In the Ajax () method, the data for the JSON type is $.param () processed
if (s.data && s.processdata && typeof s.data!== "string") { C2/>s.data = Jquery.param (S.data, s.traditional);
}
Param method
if (Jquery.isarray (a) | | (A.jquery &&!jquery.isplainobject (a))) {
  //Serialize The form elements
  Jquery.each (A, function () {
   Add (this.name, this.value);
  });
 el SE {
  //If Traditional, encode the "old" Way (the way 1.3.2 or older
  //did it) otherwise encode params vely.
  For (prefix in a) {
   buildparams (prefix, a[prefix], traditional, add);
  }
 

That's clear, if it's JSON data, then loop through it, only their Name property and the value attribute stitching strings.

If it is a normal object, loop the object's properties and then stitch the string.

Summarize:

So what this article is saying is that in jquery's Ajax functions, you can pass in 3 types of data
1. Text: "Uname=alice&mobileipt=110&birthday=1983-05-12"
2.json object: {uanme: ' Vic ', Mobileipt: ' Birthday ', ' 2013-11-11 '}
3.json array:

[
 {' name ': ' uname ', ' Value ': ' Alice '},
 {' name ': ' Mobileipt ', ' value ': ' ' ' {'} ', 
 {' name ': ' Birthday ', ' value ' : "2012-11-11"}
]

So, we can get the form and submit it in a single key, very convenient.

Add:

In fact, the extraction form data only need to serialize () method directly to get "uname=alice&mobileipt=110&birthday=1983-05-12" This is OK.

I hope this article will help you with the jquery program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.