JQuery learning tour Item10 ajax fast food

Source: Internet
Author: User
Tags getscript tojson

JQuery learning tour Item10 ajax fast food
1. Summary

This series of articles will take you into the wonderful world of jQuery. Many of them have their specific experiences and solutions. Even if you use jQuery, you can find some tips.
This article explains how to use jQuery to implement Ajax functions conveniently and quickly.

2. Preface

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.

3. Original Ajax and Ajax in jQuery

First, let's take a look at how simple Ajax implementation by jQuery is. The following is an example of using the original Ajax:

 <Script type = text/javascript> $ (function () {var xhr = new AjaxXmlHttpRequest (); $ (# btnAjaxOld ). click (function (event) {var xhr = new AjaxXmlHttpRequest (); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {document. getElementById (divResult ). innerHTML = xhr. responseText ;}} xhr. open (GET, data/AjaxGetCityInfo. aspx? ResultType = html, true); xhr. send (null) ;}) // obtain the XmlHttpRequest object function AjaxXmlHttpRequest () {var xmlHttp; try {// Firefox, Opera 8.0 +, safari xmlHttp = new XMLHttpRequest ();} catch (e) {// Internet Explorer try {xmlHttp = new ActiveXObject (Msxml2.XMLHTTP);} catch (e) {try {xmlHttp = new ActiveXObject (Microsoft. XMLHTTP);} catch (e) {alert (your browser does not support AJAX !); Return false ;}}return xmlHttp ;}</script> 
Original Ajax call 


 

In the above instance,data/AjaxGetCityInfo.aspx?resultType=htmlThe address returns an HTML code.

When using the original Ajax, we need to do a lot of things, such as creating an XmlHttpRequest object, determining the Request status, and compiling a callback function.

With jQuery's Load method, you only need one sentence:

$(#divResult).load(data/AjaxGetCityInfo.aspx, { resultType: html });

I used to be an absolute supporter of the original Ajax and even abandoned Microsoft's Asp.net Ajax, because I wanted the highest code flexibility. using the original Ajax makes it easier for me to complete my work, even if I write more code. but when I looked at other people's Ajax code and tried to modify it, I changed my opinion-our code is distributed everywhere to create functions of the XmlHttpRequest method, or some Ajax programs have poor logic and structure, which is hard to understand.

We can put common methods into a js file and tell everyone, "Hey guys, all come and use this js method ". however, in some cases, some new outsourcers do not know the existence of this js file. in fact, this general js is a public script class library. I believe no one will think it would be better to develop a class library than jQuery!

So I gave up the wheel-making plan, and everyone can use jQuery to write Ajax-related methods to solve various differences and make the work more efficient.

Now I only use jQuery's Ajax function, and my page becomes concise:

 <Script type = text/javascript src = scripts/jquery-1.3.2-vsdoc2.js> </script> <script type = text/javascript> $ (function () {$ (# btnGetHtml ). click (function (event) {$ (# divResult ). load (data/AjaxGetCityInfo. aspx, {resultType: html}) ;}}) </script> 
Use jQuery's load method 

4. jQuery Ajax details

JQuery provides several functions for sending Ajax requests. The core and most complex of these functions are:jQuery.ajax( options )All other Ajax functions are a simplified call of the function. 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

Note:

The load method can load remote HTML file code and insert it into the DOM. By default, the GET method is used. If the data parameter is passed, the Post method is used. When additional parameters are passed, the POST method is automatically converted. 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 and needs to be called in the jQuery packaging set, the returned HTML is loaded into the object, and the returned HTML is loaded even if the callback function is set.
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:
 <Script type = text/javascript src = .. /scripts/jquery-1.3.2-vsdoc2.js> </script> <script type = text/javascript> $ (function () {$ (# btnAjaxGet ). click (function (event) {// send Get request $ (# divResult ). load (.. /data/AjaxGetMethod. aspx? Param = btnAjaxGet_click + & timestamp = + (new Date ()). getTime () ;}); $ (# btnAjaxPost ). click (function (event) {// send the Post request $ (# divResult ). load (.. /data/AjaxGetMethod. aspx, {param: btnAjaxPost_click}) ;}); $ (# btnAjaxCallBack ). click (function (event) {// send the 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 response (nvidivresult).html (responseText); // or: Response (this).html (responseText) ;}); $ (# btnAjaxFiltHtml ). click (function (event) {// send a Get request and filter out the Anshan $ (# divResult) from the result ). 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

 

The preceding example demonstrates how to use the Load method.

Tip:

We should always pay attention to browser cache. When using the GET method, we should add the timestamp parameter (net Date ()). getTime () to ensure that the URLs sent each time are different, so that browser cache is avoided. when a space is added after the url parameter, for example, "", a "Unrecognized symbol" error will 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

Note:

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:
$.get(../data/AjaxGetMethod.aspx?param=btnAjaxGet_click);

Or pass the data parameter:

$.get(../data/AjaxGetMethod.aspx, { param: btnAjaxGet2_click });
The two methods have the same effect. The data parameter is automatically added to the requested 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:

function (data, textStatus) {  // data could be xmlDoc, jsonObj, html, text, etc  this; // the options for this ajax request}

Data indicates the returned data, and testStatus indicates the status code, which may be the following value: In the callback function, this is used to obtain the reference of the options object.
The type parameter refers to the data type, which may be the following values:
"Xml", "html", "script", "json", "jsonp", and "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 ")

Note:

Load JSON data using http get requests. 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:
$.getJSON(../data/AjaxGetCityInfo.aspx, { resultType: json }, function(data, textStatus){      alert(data.length);      alert(data[0].CityName);});

The string returned by the server is as follows:

[{Pkid: 0997, ProvinceId: XJ, CityName: Aksu, CityNameEn: Akesu, PostCode: 843000, isHotCity: false}, {pkid: 0412, ProvinceId: LN, CityName: Anshan, cityNameEn: Anshan, PostCode: 114000, isHotCity: false}]

In this example, I return an array using data. length can be used to obtain the number of elements in the array. data [0] accesses the first element, data [0]. cityName accesses the CityName attribute of the first element.

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

Returns: XMLHttpRequest

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

Note:

Load and execute a JavaScript file through an http get request. Before jQuery 1.2, getScript can only call JS files in the same domain. 1.2, you can call JavaScript files across domains.

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 (), getScript will pass in the type parameter with the value of "script", and finally process the request with the type as script in the Ajax function as follows:

var head = document.getElementsByTagName(head)[0];            var script = document.createElement(script);script.src = s.url;

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

head.appendChild(script);

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

      // Handle Script loading            if ( !jsonp ) {                var done = false;                // Attach handlers for all browsers                script.onload = script.onreadystatechange = function(){                    if ( !done && (!this.readyState ||                            this.readyState == loaded || this.readyState == complete) ) {                        done = true;                        success();                        complete();                        // Handle memory leak in IE                        script.onload = script.onreadystatechange = null;                        head.removeChild( script );                    }                };            }

I mainly tested cross-origin access and multi-browser support for this function. The following is the result:

The following are my key test statements used to demonstrate how to use the getScript function:

$(#btnAjaxGetJSON).click(function(event)            {                $.getScript(../scripts/getScript.js, function(data, textStatus)                {                    alert(data);                    alert(textStatus);                    alert(this.url);                });            });            $(#btnAjaxGetJSONXSS).click(function(event)            {                $.getScript(http://resource.elong.com/getScript.js, function(data, textStatus)                {                    alert(data);                    alert(textStatus);                    alert(this.url);                });            });

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

Returns: XMLHttpRequest

Note:

Load information through a remote http post request. This is a simple POST Request function to replace the complexity $.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

Note:

Load remote data using HTTP requests. JQuery underlying AJAX implementation. Easy-to-use high-level implementation $.get, $.post. $.ajax()Return 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()There is only one parameter: The parameter key/value object, which contains information about each configuration and callback function.

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.

5. Ajax-related functions.

JQuery provides related functions to assist Ajax functions.

1. jQuery. ajaxSetup (options)
No return value

Note:

Set the global AJAX default options.

Explanation:

Sometimes we want to set the default behavior of all Ajax properties on the page. Then we can use this function to set options. Then, the default options of all Ajax requests will be changed.

For example, set the default address of an AJAX request to "/xmlhttp/", disable triggering of a global AJAX event, and use POST instead of the default GET method. In subsequent AJAX requests, no option parameters are set:

$.ajaxSetup({  url: /xmlhttp/,  global: false,  type: POST});$.ajax({ data: myData });

2. serialize ()

Returns: String

Note:

The content of a sequence table is a string used for Ajax requests. Serialization is most commonly used when form data is sent to the server. the serialized data is in a standard format and can be supported by almost all servers. to work properly as much as possible, all serialized form fields must have the name attribute, and only one eid cannot work.

Write the name attribute like this:

 

Explanation:

The serialize () function concatenates form objects in the form object to be sent to the server into a string. it is easy for us to obtain form data when sending data using Ajax. this is similar to when a From object is submitted in Get mode, the name/value of the form object is automatically put on the url for submission.
For example, a form:

The generated string is single = Single character m = Multiple character m = Multiple3 & check = check2 & radio = radio1.

3. serializeArray ()

Returns: Array

Note:

Serialized table elements (similar to the '. serialize ()' method) return JSON data structure data. Note that this method returns a JSON object instead of a JSON string. You need to use plug-ins or third-party libraries for string-based operations.

Explanation:

I was disappointed to see the instructions. I used this function to obtain a JSON object, but jQuery does not provide a method to convert a JSON object to a JSON string.
No suitable JSON compiler is found on the JSON official website, and the jquery plug-in jQuery. json is selected:
Http://code.google.com/p/jquery-json/

It is very easy to use:

var thing = {plugin: 'jquery-json', version: 1.3};var encoded = $.toJSON(thing);              //'{plugin: jquery-json, version: 1.3}'var name = $.evalJSON(encoded).plugin;      //jquery-jsonvar version = $.evalJSON(encoded).version;  // 1.3

Use serializeArray ()$.toJSONMethod, we can easily obtain the json of the form object and convert it to a JSON string:

$(#results).html( $.toJSON( $(form).serializeArray() ));

Result:

[{name: single, value: Single}, {name: param, value: Multiple}, {name: param, value: Multiple3}, {name: check, value: check2}, {name: radio, value: radio1}]
6. Global Ajax events

In the options parameter attribute of jQuery. ajaxSetup (options), there is a global attribute: global Value Type: Boolean value, default value: true,

Note:
Whether to trigger a global Ajax event.
This attribute is used to set whether to trigger a global Ajax event. A global Ajax event is a series of events that accompany Ajax requests. The main events include:

First column Column 2
AjaxComplete (callback) Execute the function when the AJAX request is complete.
AjaxError (callback) Execute the function when an error occurs in the AJAX request.
AjaxSend (callback) Execute the function before sending an AJAX request
AjaxStart (callback) Execute functions at the beginning of an AJAX request
AjaxStop (callback) Execute the function at the end of the AJAX request
AjaxSuccess (callback) Execute the function when the AJAX request is successful.

Use an example to explain the trigger sequence of each event:

 <Script type = text/javascript src = .. /scripts/jquery-1.3.2.min.js> </script> <script type = text/javascript> $ (document ). ready (function () {$ (# btnAjax ). bind (click, function (event) {$. get (.. /data/AjaxGetMethod. aspx) ;}) $ (# divResult ). ajaxComplete (function (evt, request, settings) {$ (this ). append ('ajaxcomplete');}) $ (# divResult ). ajaxError (function (evt, request, settings) {$ (this ). append ('ajaxerror');}) $ (# divResult ). ajaxSend (function (evt, request, settings) {$ (this ). append ('axaxput');}) $ (# divResult ). ajaxStart (function () {$ (this ). append ('axaxstart');}) $ (# divResult ). ajaxStop (function () {$ (this ). append ('ajaxstop');}) $ (# divResult ). ajaxSuccess (function (evt, request, settings) {$ (this ). append ('ajaxsuccess ') ;}}); </script> 

Send Ajax request
 

Result:

You can set the global attribute of the default options to false to cancel the triggering of global Ajax events.

7. Note: if there are two parameters with the same name in the url sent by the Get request, for example, two param parameters:
Http: // localhost/AjaxGetMethod. aspx? Param = Multiple merge m = Multiple3
Use the server method to obtain the param parameter:
if (!String.IsNullOrEmpty(HttpContext.Current.Request[Param]))        {            param = HttpContext.Current.Request[Param];        }

At this time, the obtained param is a string separated:
Multiple, Multiple3

8. Summary

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. in addition, it explains the auxiliary functions of ajax, such as the serialize () method used to serialize form objects as strings, and the serializeArray () method used to serialize form objects into JSON objects. it is useful to use scripts to obtain data and implement interaction with the server. JSON-format data frees us from messy attribute strings when processing large object programming.

JQuery also provides a special event for inputting global ajax events, and you can set these events on an object to call these events in each lifecycle of an Ajax request, you can enable or disable global events by modifying the global attribute of the default options object.

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.