Ajax usage in jQuery

Source: Internet
Author: User
Ajax enriches user pages and enhances user experience. ajax is a required course for all Web development. although Ajax technology is not complex, the implementation method is different for every developer. jQuery provides a series of Ajax functions to help us unify this difference and make it easier to call Ajax. jQuery provides several functions for sending Ajax requests.

Ajax enriches user pages and enhances user experience. ajax is a required course for all Web development. although Ajax technology is not complex, the implementation method is different for every developer. jQuery provides a series of Ajax functions to help us unify this difference and make it easier to call Ajax. jQuery provides several functions for sending Ajax requests. among them, the core and most complex is jQuery. ajax (), all other Ajax functions are a simplified call of it. you can use this result when you want to fully control Ajax. Otherwise, it is more convenient to use simplified methods such as get, post, and load. therefore, jQuery. put the ajax (options) method in the last introduction. first, we will introduce the simplest load method:

1. load (url, [data], [callback])

Returns: jQuery package set description

The load method can load remote HTML file code and insert it into the DOM.

The GET method is used by default. If the data parameter is passed, the Post method is used.

The POST method is automatically converted when additional parameters are passed. In jQuery 1.2, you can specify a selector to filter loaded HTML documents. In DOM, only filtered HTML code is inserted. The syntax is like "url # some> selector". The default selector is "body> *".

Explanation:

Load is the simplest Ajax function, but its usage has limitations:

It is mainly used to directly return HTML Ajax interfaces.

Load is a jQuery packaging set method. It needs to be called in the jQuery packaging set and will load the returned HTML to the object, even if the callback function is set, it will still load.

However, it is undeniable that the load interface is cleverly designed and easy to use. The following uses an example to demonstrate the use of the Load interface:

 

 

JQuery Ajax-Load 

Script

$ (Function ()

{

$ ("# BtnAjaxGet"). click (function (event)

{

// Send a Get request

$ ("# DivResult"). load ("../data/AjaxGetMethod. aspx? Param = btnAjaxGet_click "+" & timestamp = "+ (new Date (). getTime ());

});

$ ("# BtnAjaxPost"). click (function (event)

{

// Send a Post request

$ ("# DivResult"). load ("../data/AjaxGetMethod. aspx", {"param": "btnAjaxPost_click "});

});

$ ("# BtnAjaxCallBack"). click (function (event)

{

// Send a Post request, and then execute the callback function.

$ ("# DivResult"). load (".../data/AjaxGetMethod. aspx", {"param": "btnAjaxCallBack_click"}, function (responseText, textStatus, XMLHttpRequest)

{

ResponseText = "Add in the CallBack Function!
"+ ResponseText

$ ("# DivResult" ).html (responseText); // or: Response (this).html (responseText );

});

});

$ ("# BtnAjaxFiltHtml"). click (function (event)

{

// Send a Get request and filter out the "Anshan" item from the result

$ ("# DivResult"). load ("../data/AjaxGetCityInfo. aspx? ResultType = html "+" & timestamp = "+ (new Date (). getTime () +" ul> li: not (: contains ('anshan '))");

});

})

Script

 

 

Use Load to execute Get requests  

Use Load to execute Post requests  

Use the Load method with callback function  

Use selector to filter the returned HTML content 

 

 

 

Tip: We should always pay attention to browser cache. When using the GET method, we should add the timestamp parameter (netDate ()). getTime () to ensure that the URLs sent each time are different, so that browser cache is avoided.

Tip: when a space is added after the url parameter, for example, "", the error "unidentifiable symbol" may occur, and the request can still be sent normally. however, HTML cannot be loaded to the DOM. solve the problem after deletion.

2. jQuery. get (url, [data], [callback], [type])

Returns: XMLHttpRequest description:

Load information through a remote http get request.

This is a simple GET request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. ajax.

Explanation:

This function sends a Get request. parameters can be directly spliced in URLs, for example:

Script

$. Get ("../data/AjaxGetMethod. aspx? Param = btnAjaxGet_click ");

Script

Or pass the data parameter:

Script

$. Get ("../data/AjaxGetMethod. aspx", {"param": "btnAjaxGet2_click "});

Script

The two methods have the same effect. The data parameter is automatically added to the request url. If a parameter in the url is passed through the data parameter, the parameters with the same name are not automatically merged. the callback function signature is as follows:

Script

Function (data, textStatus ){

// Data cocould be xmlDoc, jsonObj, html, text, etc...

This; // the options for this ajax request

}

Script

Data indicates the returned data, and testStatus indicates the status code, which may be the following values:

"Timeout", "error", "notmodified", "success", "parsererror"

In the callback function, this is used to obtain the reference of the options object. For more information about options, see:

Http://docs.jquery.com/Ajax/jQuery.ajax#options

The type parameter refers to the data type, which may be the following values:

"Xml", "html", "script", "json", "jsonp", "text ".

The default value is "html ".

The jQuery. getJSON (url, [data], [callback]) method is equivalent to jQuery. get (url, [data], [callback], "json ")

3. jQuery. getJSON (url, [data], [callback])

Returns: XMLHttpRequest

Equivalent to: jQuery. get (url, [data], [callback], "json ")

Description: loads JSON data through an http get request.

In jQuery 1.2, you can use a callback function in the form of JSONP to load JSON data of other domains, such as "myurl? Callback =? ". Will jQuery be replaced automatically? For the correct function name to execute the callback function.

Note: The Code after this row will be executed before the callback function is executed.

Explanation:The getJSON function only sets the type parameter of the get function to "JSON". The data obtained in the callback function is already an object parsed in JSON format:

Script

$. GetJSON ("../data/AjaxGetCityInfo. aspx", {"resultType": "json"}, function (data, textStatus)

{

Alert (data. length );

Alert (data [0]. CityName );

});

Script

The string returned by the server is as follows:

Script

[{"" Pkid "": "0997" "," "ProvinceId" ":" "XJ" "," "CityName" ":" "Aksu "", "" CityNameEn "": "" Akesu "", "" PostCode "": "843000" "," "isHotCity" ": false },

{"" Pkid "": "0412" "," "ProvinceId" ":" "LN" "," "CityName" ":" Anshan "", "" CityNameEn "": "" Anshan "", "" PostCode "": "114000" "," "isHotCity" ": false}]

Script

4. jQuery. getScript (url, [callback])

Returns: XMLHttpRequest

Equivalent to: jQuery. get (url, null, [callback], "script ")

Note: an http get request is used to load and execute a JavaScript file.

Before jQuery 1.2, getScript can only call JS files in the same domain. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts simultaneously in the global scope. If you use getScript to add a script, add the latency function.

Explanation:

In the past, when I used the dojo class library, the official default file does not support cross-origin. In the end, I gave up using dojo (although I found a cross-origin version on the Internet, it was not perfect ). so I did some research on the core implementation and use of this function.

First, understand the jQuery internal implementation of this function, and still use the get function. All Ajax functions of jQuery, including get, are used at last. ajax () and getScript pass in the type parameter with the value of "script". Finally, the Ajax function processes the request with the type as script as follows:

Script

Var head = document. getElementsByTagName ("head") [0];

Var script = document. createElement ("script ");

Sscript. src = s. url;

Script

The above code dynamically creates a script statement block and adds it to the head:

Script

Head. appendChild (script );

Script

After the script is loaded, delete it from the head:

Script

// Handle Script loading

If (! Jsonp ){

Var done = false;

// Attach handlers for all browsers

Scriptscript. onload = script. onreadystatechange = function (){

If (! Done &&(! This. readyState |

This. readyState = "loaded" | this. readyState = "complete ")){

Done = true;

Success ();

Complete ();

// Handle memory leak in IE

Scriptscript. onload = script. onreadystatechange = null;

Head. removeChild (script );

}

};

}

Script

5. jQuery. post (url, [data], [callback], [type])

Returns: XMLHttpRequest

Description: loads information through a remote http post request.

This is a simple POST Request function to replace complex $. ajax. You can call the callback function when the request is successful. To execute a function when an error occurs, use $. ajax.

Explanation:The specific usage is the same as get, but the submission method is changed from "GET" to "POST ".

6. jQuery. ajax (options)

Returns: XMLHttpRequest

Description: loads remote data through an HTTP request.

JQuery underlying AJAX implementation. For easy-to-use high-level implementation, see $. get, $. post, and so on.

$. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this object, but in special cases it can be used to manually terminate the request.

$. Ajax () has only one parameter: The parameter key/value object, which contains information about various configurations and callback functions. For detailed Parameter options, see.

Note: If you specify the ype option, make sure that the server returns the correct MIME information (for example, xml returns "text/xml "). Incorrect MIME types may cause unpredictable errors. See Specifying the Data Type forAJAX Requests.

NOTE: If dataType is set to "script", all remote (not under the same domain name) POST requests will be converted to GET requests. (Because the script tag of DOM will be used for loading)

In jQuery 1.2, you can load JSON data across domains. You need to set the data type to JSONP during use. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function. When the data type is set to "jsonp", jQuery automatically calls the callback function.

Explanation:

This is the core function of Ajax in jQuery. All the above functions that send Ajax requests will call this function at last. the options parameter supports many parameters, which can be used to completely control ajax requests. the this object in the Ajax callback function is also an options object.

Because the most commonly used or simplified get and post functions, so here does not explain the options parameter in detail. options parameter documentation see: http://docs.jquery.com/Ajax/jQuery.ajax#options

This article describes how to use jquery to implement Ajax functions. the gradient Ajax methods used to send Ajax requests, such as load, get, getJSON, and post are not described too much in the core ajax methods, ajax requests are fully controlled by configuring complex parameters.

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.