Jquery.ajax () The data parameter type example detailed _jquery

Source: Internet
Author: User

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 cell primes or objects of a table.
parameter
obj,[traditional]
arrays or jquery objects are serialized according to Name/value, and ordinary objects are serialized according to Key/value pairs.
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.

The usage summary of the data parameter of Ajax method in Ps:jquery

 $.ajax ({type:post, url:some.php, Data:name=john&location=boston,///first method of reference Data: {Name:john,location:boston}//second mode of reference//data: {FOO:[BAR1, bar2]} converted to ' &foo=bar1&foo=bar2 '///The first kind we use your
 L The parameter inside if add with & this symbol, may not receive or incomplete, such as "Data:name=john&location=boston," if the name value is John&smith This may be a problem,
  We can use JS inside the encodeURIComponent () method to escape, but if the use of data: {Name:john,location:boston} This way to write words do not need to escape, if the escape, the receiver will be escaped after the string * *
  Success:function (msg) {alert (Data saved: + msg); 
}
});
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.