JQuery Ajax Usage Summary

Source: Internet
Author: User
Tags http post

I. Overview

  jquery encapsulates Ajax operations, $.ajax () is the lowest-level method in jquery, and the 2nd layer is the load (),$.get () , and $.post () methods , the third layer is the $.getscript () and $.getjson () methods.

  notation: Load (URL, [data], [callback])

url:string Type-the URL address of the request HTML page

Data:object type-key/value data sent to the server

Callback:function Type-The Destroy function when the request completes, whether the request succeeds or fails.

Second, load () method

1. Overview

  The load () method is the most common and simple Ajax method in jquery.

  Can load remote HTML files and insert them into the DOM.

2. Delivery method

  The load () method is passed based on the parameter data.

By default, the Get mode is used to automatically convert to the Post method when additional parameters are passed.

3. Parameters

  Object Type-key/value data sent to the server.

4. Callback function

  The load () method provides a callback function that has three parameters for operations that must be completed before the load can continue.

ResponseTest: The content returned by the request.

Textstatus: The status of the request, there are success, error, notmodified, timeout 4 kinds.

The Xmlhttprequest:xmlhttprequest object.

5. Example

①get Way

$ ("#feeds"). Load ("feeds.html");

②post Way

$ ("#feeds"). Load ("feeds.php", {limit:25}, function (ResponseText, textstatus, XMLHttpRequest) {   alert ("The last 25 Entries in the feed has been loaded "); });

Third, Get method

1. Overview

  The $.get () method uses the Get method to make a one-step request.

  notation: $.get (URL, [data], [callback], [type]).

2. Parameters

  Url:string type-The URL address of the requested HTML page.

Data:object Type-The Key/value data sent to the server is appended as QueryString to the request URL.

Callback: Executes the callback function when loading succeeds (only if the method is called when the response's return state success) automatically passes the result and state of the request to the method. If you need to execute a function on an error, you need to use the $.ajax () method.

3. Callback function

  The callback function is not called until the data is successfully returned, unlike the load () method. 

The callback function of the $.get () method has only two parameters.

Data: The content returned by the request.

Textstatus: The status of the request.

4. Return content Format

  XML, HTML, JSON, script, text _default.

5. Example

① Returning HTML fragments

$ ("#send"). Click (function () {$.get ("get1.asp", {username:  $ ("#username"). Val (), Content:  $ ("#content"). Val ()  }, function (data, textstatus) {                        $ ("#resText"). HTML (data);//Add the returned data to the page})

Because the data format returned by the server side is an HTML fragment, you do not need to be processed to insert the new HTML data into the main page.

② returning an XML document

$ ("#send"). Click (function () {                $.get ("get2.asp", {                    Username: $ ("#username"). Val (),                    content: $ ("#content "). Val ()                }, function (data, textstatus) {                    var username = $ (data). Find (" comment "). attr (" username ");                    var content = $ (data). Find ("comment content"). text ();                    var txthtml = "<div class= ' comment ' >

Because the data format returned by the server side is an XML document, the returned data needs to be processed.

③ returning a JSON file

$ ("#send"). Click (function () {                $.get ("get3.asp", {                    Username: $ ("#username"). Val (),                    content: $ ("#content "). Val ()                }, function (data, textstatus) {                    var username = data.username;                    var content = data.content;                    var txthtml = "<div class= ' comment ' >

Because the data format returned by the server side is a JSON file, the returned data needs to be processed before the new HTML data can be added to the main page.

④ when it is not necessary to share data with other applications, it is generally easiest to use HTML fragments to provide return data, and if reuse is needed, the JSON file is a good choice for performance and file size advantages, and when the remote application is unknown, the XML document is a wise choice, It is "Esperanto" in the domain of Web services.

Iv. $.post () method

1. Overview

  The method is used similar to the $.get () method. The difference is that the information is loaded via an HTTP POST request.

  notation: $.post (URL, [data], [callback], [type])

2. Differences from the $.get () method

The Request object function is to obtain the data from the client, the commonly used three ways to obtain data are: Request.Form, request.querystring,request. The third is an abbreviation for the first two, which can replace the first two cases. The first two main corresponding form submissions are two different methods of submission: The Post method and the Get method, respectively.

  The $.get () method can obtain parameters by request.querystring["A" and request["a"];

The $.post () method can only get parameters by request["a".

V. $.ajax () method

1. Overview

The jquery underlying AJAX implementation, $.ajax () returns the XMLHttpRequest object it created.

  The $.ajax () method not only implements the same functions as the $.load (), $.get (), and $.post () methods, but can also set the Beforesend (pre-commit callback function), error (post-request processing), and success (processing after the request succeeds) and the complete (post-request processing) callback function, which gives the user more information about the AJAX message.

  Wording: $.ajax (options)

2. Parameters

(1)url:string type-(default current address) send the requested address

Type:string Type-The request method, the default is get.

Timeout:number type-Sets the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method

Data:object or String type-data sent to the server. If it is not a string, it is automatically converted to a string format. The GET request will be appended to the URL. For example: {foo1: "Bar1", Foo2: "Bar2"} is converted to &FOOL=BAR1&FOO2=BAR2.

Datatype:string type-The data type that is expected to be returned by the server. if not specified, jquery automatically returns Responsexml or ResponseText based on the HTTP packet mime information and is passed as a callback function parameter.

The following types are available: XML, HTML, script, JSON, JSONP, text

Global:boolean Type-default is true. Indicates whether to start the global Ajax event. Setting false will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.

(2) Callback function: function type

If you are working with $.ajax () data, you need to use a callback function. Beforesend, error, Datafilter, success, complete.

    • Beforesend: called before the request is sent, and a xmlhttprequest is passed as a parameter. If you return False in Beforsend, you can cancel this Ajax request
      • function (XMLHttpRequest) {      this;//the options parameter passed when calling this Ajax request  } 
  • error: Called when the request is faulted. 3 parameters, passing in a XMLHttpRequest object, a string describing the type of error, and an exception object (if any)
    • function (XMLHttpRequest, textstatus, Errorthrown) {    //normally textstatus and Errorthown only one of them contains information    this;// The options parameter passed when calling this Ajax request  } 
  • Datafilter: called after the request succeeds. The returned data is passed in as well as the value of the "DataType" parameter. and the new data (possibly processed) must be returned to the success callback function.
  • success: called after the request. The data after the incoming return, and the string containing the success code.
    • function (data, textstatus) {     //data is returned by the server and is based on the datatype parameter. It may be xmldoc, jsonobj, HTML, text, and so on.     this;//The options parameter passed when calling this Ajax request  } 
       
  • Complete : This function is called when the request is completed, regardless of success or failure. The incoming XMLHttpRequest object, and a string containing the success or error code.
    • function (XMLHttpRequest, textstatus) {           this;//the options parameter passed when calling this Ajax request  }  

VI. Serialization of elements

1.serialize () method

When a form is submitted, the serialized form content is a string .

$ ("#send"). Click (function () {     $.get ("get1.php", $ ("#form1"). Serialize (), Functiuon (data, Textstatus) {             $ ( "#restText"). HTML (data);     });

2.serializeArray () method

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

Note: This method returns a JSON object rather than a JSON string. You need to use a plug-in or a third-party library for string manipulation.

The returned JSON object consists of an array of objects, each of which contains one or two name-value pairs--name and value parameters if value is not empty.

Eg:

  [          {name: ‘firstname‘, value: ‘Hello‘},          {name: ‘lastname‘, value: ‘World‘}    ]

3.$.param () method

It is the core of the Serialize () method, which is used to serialize an array or an object according to Key/value.

eg

var obj = {a:1, b:2, C:3};var k = $.param (obj); alert (k);//Output a=1&b=2&c=3

JQuery Ajax Usage Summary

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.