Chapter 6 jQuery and Ajax applications

Source: Internet
Author: User
Tags getscript

1. XMLHttpRequest object of Ajax

XMLHttpRequest is the core of Ajax and is the key to Ajax implementation. It is used to send asynchronous requests, receive responses, and execute callbacks. XMLHttpRequest was first referenced in Microsoft Internet Explorer 5.0 ActiveX components.

2. Ajax in JQuery

JQuery encapsulates Ajax. In jQuery, $. the ajax () method is the underlying method. The second layer is load (), $. load () and $. the post () method. The third layer is $. getScript () and $. getJSON () method.

2.1 load () method

Structure: load (url [, data] [, callback])

Parameter explanation: parameters of the load () method

Parameter Name Type Description
Url String Request the URL of the HTML page
Data (optional) Object Key/value sent to the server
Callback (optional) Fucntion The callback function when the request is complete, whether the request is successful or fails.

 

Transmission Mode: the load () method is automatically set based on the parameter data. If no parameter is transmitted, the GET method is used for transmission. Otherwise, the method is automatically converted to POST.

Callback Function: load () provides a callback function. This function has three parameters, representing the content returned by the request, the Request status, and the XMLHttpRequest object. jQuery code

As follows:

$ ("ResText "). load ("test.html", function (responseText, textStatus, XMLHttpRequest) {// responseText: Content returned by the request // textStatus: Request status: success, error, notmodified, timeout4 // XMLHttpRequest: XMLHttpRequest object })
/// Call the callback function when the request is complete.

2.2 $. get () and $. post () Methods

2.2.1 $. get ()

Structure: $. get (url [, data] [, callback] [, type])

Parameter explanation: $. get () method parameter explanation

Parameter Name Type Description
Url String Request the URL of the HTML page
Data (optional) Object The key/value data sent to the server will be appended to the request URL type as QueryString
Callback (optional) Fucntion After loading successfully, the callback function (success calls this method only when Response returns the status) automatically passes the request results and status to this method.
Type (optional) String The format of the content returned by the server, including xml, html, script, json, text, and _ default.

Sample Code:

$ ("# Send "). click (function () {$. get ("get1.php", {username: "Zhang San"}, function (data, textStatus) {// data: the returned content can be XML documents, JSON files, Html fragments, and so on. // TextStatus: Request status: success, error, notmodified, timeout. }, Type );});

// The content returned by the data parameter request. It is called only when textStatus is success, which is different from the load method.

2.2.1 $. post ()
The usage is the same as $. get (), but they still have the following differences.

      • The GET request will pass the parameters following the URL, while the POST request will be sent to the Web server as the entity content of the HTTP message.
      • The GET method has a limit on the size of the transmitted data (generally not more than 2 kb), while the data transmitted in the POST method is much larger than the GET method. (Theoretically unlimited)
      • Data requested by the GET method will be cached by the browser, and POST can avoid these problems.
      • The GET and POST methods also obtain different data on the server.

2.3 $ getScript () method and $. getJson () method ---- No sorting.

2.4 $. ajax () method

Structure: $. ajax (options)

Parameters:

Parameter Name Type Description
Url String (The current page by default) the address of the put request.
Type String

Request Method (POST or GET ). The default value is GET. Pay attention to other HTTP requests.

For example, PUT and DELETE can also be used, but only some browsers support

Timeout Number Set the request timeout (in milliseconds ). This setting overwrites the $. ajaxSetup () method and global settings.
Data Object or String

If the data on the sending server is no longer a string, it is automatically converted to the string format. The GET request will be appended

URL. To prevent this automatic conversion, you can view the processData option. The object must be key/value, for example:

{Fool: "bar1", foo2: "bar2"} is converted to & foo1 = bar1 & foo2 = bar2. If it is an array, jQuery

Different values will automatically correspond to the same name. For example, {foo: ["bar1", "bar2"]} is converted to & foo = bar1 & foo = bar2

DataType String

Expected type returned by the server. If this parameter is not specified, jQuery automatically returns responseXML Based on the MIME information of the HTTP package.

Or responseText, which is passed as the callback function parameter.

Xml: the xml document is returned and can be processed by jQuery.

Html: returns the HTML information of the stored text. The script tag is executed when the DOM is inserted.

Script: the Javascript code of the stored text is returned, and the results are not automatically cached. Unless the cache parameter is set. Note:

During remote requests (not in the same domain), all POST requests are converted to GET requests.

Json: Return json data.

Jsonp: JSONP format. When calling a function in the form of JSONP, such as myUrl? Callback = ?, JQuery will automatically

Replace the last "?" The callback function has been executed for the correct function name.

Text: returns the stored text string.

 

BeforeSend Function

Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. In beforeSend

If false is returned, the Ajax request can be canceled. The XMLHttpRequest object is a unique parameter.

Function (XMLHttpRequest ){

This; // The options parameter passed when calling this Ajax request

}

Complete Function

Callback Function called after the request is complete (the request is successful or the request fails to be called)

Parameter: XMLHttpRequest object and a string that describes the successful request type.

Function (XMLHttpRequest, textStatus ){

This; // The options parameter passed when calling this Ajax request

}

Succes Function

The callback function called after the request is successful. There are two parameters.

(1) data returned by the server and processed according to the dataType parameter.

(2) A string describing the status

Function (fata, textStatus ){

// Data may be xmlDoc, jsonObj, text, etc.

This; // The options passed when calling this Ajax request

}

Error Function The callback function called after a request failure has three parameters.

XMLHttpRequest object, error message, and captured error object (optional ).

The Ajax event functions are as follows.

Function (XMLHttpRequest, textStatus, errorThrown ){

// Generally, textStatus and errorThrown only contain one of the information.

This; // The options passed when calling this Ajax request

}

Global Function

The default value is true. Indicates whether to trigger a global Ajax event. Setting false does not trigger global Ajax events,

AjaxStart or AjaxStop can be used to control various Ajax events.

2.5 serialization Element

2.5.1 serialize () method

Example: The form HTML code is as follows:

<Form id = "form1" action = "#"> <p> comment: </p> <p> Name: <input type = "text" name = "username" id = "username"/> </p> <p> is the same: <input type = "text" name = "content" id = "content"/> </p> <input type = "button" id = "send" value = "Submit"/> </p> </form>HTML code

To obtain the name and content, you must add the fields one by one to the data parameters. The Code is as follows:

$ ("# Send "). click (function () {$. get ("get1.php", {username: $ ("# username "). val (), content: $ ("# content "). val ()}, function (data, textStatus) {/// Execution Code })})

This method is barely usable in forms with a small number of fields, but if the form is complex, this will add workload. Serialize () can solve these problems. You just need to change the code to the following:

$ ("# Send "). click (function () {$. get ("get1.php", $ ("# form1 "). serialize (), function (data, textStatus) {// Execution Code })})

 

 

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.