Cliché Ajax

Source: Internet
Author: User
Tags getscript http authentication xml dom document

jquery has a great deal of Ajax encapsulation, and jquery uses a three-tier package: The bottom-up package is: $.ajax () further encapsulates the three methods of the second layer through the bottom layer:. Load (), $.get (), $.post () the highest level is: $. GetScript () and $.getjson ()
My own Memory Method: $.ajax () is an asynchronous process of origin, it is a region, a village, a small ecosystem, is a branch of jquery, $.get () is to obtain, obtain, that is, to our ecosystem to transport our ecosystems do not have things; $.post () is to take things that we cannot consume completely, to change what we need; one in charge of the input, one in charge of the output, then a steward is needed to manage itself, and. Load () is the housekeeper who manages the ecosystem, because it does not need to go out, only in its own activities, so it does not have to fight, The logo=>$ of the jquery company. Because we have the goods are important, there are secondary, so that the birth of VIP services, $.getscript () and $.getjson () These two special channels for VIP services, convenient and fast
"1". The Laod () method has three parameters: 1. URL: must, request the URL address of the HTML file, the parameter type is String2. Data: Optional, sent Key/value, parameter type OBJECT3. Callback: Optional, successful or failed callback function with parameter type function
Example: Get mode: Do not pass data, the default get way $ ('. Ajax_btn '). On (' click ', Function () {    $ ('. Ajax_box '). Load (' Ajax.php?url=snail ', function () {        alert (' I am the callback function! ');});    
<?phpif ($_get[' url ']== ' snail ') {    echo ' snail ';} else{    echo ' Other animals! ‘;}? >
Post mode: Pass data to the Post mode $ ('. Ajax_btn '). On (' click ', Function () {    $ ('. Ajax_box '). Load (' ajax.php ', {        URL: ') Snail ',    },function () {        alert (' I am the callback function! ');});    
<?phpif ($_post[' url ']== ' snail ') {    echo ' snail ';} else{    echo ' Other animals! ‘;}? >
After the AJAX data is loaded, you can execute the callback function callback, which is the third parameter, the callback function can pass three optional parameters: ResponseText (Request return), Textstatus (Request state), XMLHttpRequest ( XMLHttpRequest object)
$ ('. Ajax_btn '). On (' click ', Function () {    $ ('. Ajax_box '). Load (' ajax.php ', {        URL: ' snail ',    },function ( RESPONSE,STATUS,XHR) {        Console.log (' returned value is: ' +response+ ', the status is: ' +status+ ', the state is: ' +xhr.statustext ');        The values returned are: Snail, Status: Success, Status: OK        console.log (' return value: ' +xhr.responsetext+ ', XML DOM document: ' +xhr.responsexml+ ', HTTP status of the response: ' +xhr.status+ ', HTTP status description: ' +xhr.statustext ';        The value returned by index.html:36 is: snail, XML dom document: Undefined, HTTP status of the response: 200,http status Description: OK    });
<?phpif ($_post[' url ']== ' snail ') {    echo ' snail ';} else{    echo ' Other animals! ‘;}? >
Note: The status gets the value if the data returned successfully is: success, otherwise: error. The XMLHttpRequest object belongs to JavaScript extend, and some properties can be called as follows:
The property name            description ResponseText     The text returned as the response body Responsexml      If the response principal content type is "Text/xml" or "Application/xml", the XML containing the response data is returned           description of the HTTP status StatusText       HTTP status for DOM document status response
Return data status and statustext table: HTTP status Code     status string                  description                        The server successfully returned to page bad           Request               A syntax error causes the server to not recognize the 401           unauthorized              request requires user authentication 404           not found the                 specified URL cannot be found on the server     the error server encountered an unexpected error and could not complete the request 503           serviceunavailable The        request could not be completed due to server overload or maintenance
"2" $.get () and $.post (). The load () method is a local method because it requires a JQuery object that contains an element as a prefix. While $.get () and $.post () are global methods, you do not need to specify an element. Use aspect:. Load () is suitable for asynchronous fetching of static files, and $.get () and $.post () are more appropriate for parameters that need to be passed to the server page.
The $.get () method has four parameters: the first three and. Load () have one more of the four parameter type, which is the content format returned by the server: XML, HTML, script, JSON, JSONP, and text are required parameters, followed by three optional parameters
$ ('. Ajax_btn '). On (' click ', Function () {    $.get (' ajax.php ', {        URL: ' snail ',    },function (Response,status, XHR) {        if (status== ' success ') {            $ ('. Ajax_box '). HTML (response);        }        Type automatically converted to text    });

Note: The fourth parameter type is the type that specifies the asynchronous return. In general, the type parameter is intelligent judgment, do not need us to set the initiative, if the active setting, it will be forced to return in the specified type format.

$ ('. Ajax_btn '). On (' click ', Function () {    $.get (' Ajax.xml ', {        URL: ' snail ',    },function (response, STATUS,XHR) {        if (status== ' success ') {            $ ('. Ajax_box '). HTML (response);        }        Type automatically converted to XML    });

Note: If you are loading an XML file, type will be smart to judge. If you force the HTML type to return, the XML file will be returned as normal data without parsing the data in XML format.

The use of $.post () method and $.get () are basically consistent, the difference between them is more obscure, the basic is the difference behind, in the user's use can not be reflected. The specific differences are as follows: The 1.GET request is submitted via a URL, while the POST request is submitted by the HTTP message entity, the 2.GET commit has a size limit (2KB), and the post is unrestricted, the 3.GET method is cached, there may be security issues, and post does not have this problem; 4.GET is obtained via $_get[], POST via $_post[].
$ ('. Ajax_btn '). On (' click ', Function () {    $.post (' ajax.php ', {        URL: ' snail ',    },function (Response,status, XHR) {        if (status== ' success ') {            $ ('. Ajax_box '). HTML (response);        }})    });
$.getscript () and $.getjson () =>jquery provide a set of methods for a specific asynchronous load: $.getscript (), which loads a specific JS file, and $.getjson (), which is used to load the JSON file specifically.
$ ('. Ajax_btn '). On (' click ', Function () {    $.getscript (' ajax.js ');}); $ ('. Ajax_btn '). On (' click ', Function () {    $.getjson (' Ajax.json ', function (RESPONSE,STATUS,XHR) {        Console.log (response.ajax.name);});    

$.ajax () is the lowest-level method in all Ajax methods, and all other methods are based on the encapsulation of the $.ajax () method.
This method has only one parameter, passing an object of each function key-value pair.

$.ajax () method object parameter table:

Parameter type description URL string send request address type string Request Way :P Ost or GET, the default gettimeout number sets the time to request timeout (in milliseconds) for data object or string sent to the server, object or key value pair string da Tatype String Returns the data type, such as HTML, XML, JSON, etc. beforesend function can modify the XMLHttpRequest object before sending the request The callback function that is called after the complete function request has completed seccess the call to the functions request after it is successful error funct The callback function called when Ion request fails global Boolean defaults to True to indicate whether to trigger globally Ajaxcache Boolean settings The browser caches the response, which defaults to true. False if the datatype type is script or JSONP. The content DOM specifies that an element is the context of all the callback functions associated with the request. The ContentType String specifies the type of the requested content. The default is application/x-www-form-urlencoded. Async Boolean is handled asynchronously. The default is true,false for synchronous ProcessData Boolean by default to True, data is processed as a URL encoding format. If False, prevents incoming data processing from being a URL-encoded format. The Datafilter Function is used to filter the responseThe callback function for the data. Ifmodified Boolean defaults to False, without header detection. If true, the header is detected and the request is considered successful when the corresponding content is changed from the last request. JSONP String Specifies a query parameter name to override the default Jsonp callback parameter name callback.     Username string The user name used in the HTTP authentication request password string The password used in the HTTP authentication request Scriptcharset String sets the character set used to set script and JSONP requests when the remote and local content uses different character sets. The XHR function is used to provide callback functions for XHR instance custom implementations traditional Boolean defaults to false and does not use traditional style parameter serialization. If true, it is used.
$ ('. Ajax_btn '). On (' click ', Function () {    $.ajax ({        type: "GET",        URL: "ajax.php",        data:{            URL: " Snail ",        },        success:function (response,status,xhr) {            console.log (response);        }    )});

Note: For the Data property, if it is a get mode, you can use three of the three forms that were previously said. If the post mode can use the previous two forms.

I. Load requests when the AJAX sends the request asynchronously, when the network speed is slow, there will be a long request time problem. When a request exceeds a certain time, the user becomes impatient and closes the page. And if the user can be prompted during the request, for example: trying to load ..., then the same request time will make the user experience better.
Query provides two global events,. Ajaxstart () and. Ajaxstop (). Both global events, as long as the user triggers Ajax, is activated when the request starts (not completing other requests). Ajaxstart (), the request ends (all requests are ended). Ajaxstop ().
$ ('. Ajax_load '). Ajaxstart (function () {    $ (this). Show ();}). Ajaxstop (function () {    $ (this). Hide ();});

Note: The above code is not valid in jQuery1.8 and later versions and needs to be jquery-migrate backwards compatible to run. In the new version, you must bind to the document element.

$ (document). Ajaxstart (function () {    $ ('. Ajax_load '). Show ();}). Ajaxstop (function () {    $ ('. Ajax_load '). Hide ();});
The request time is too long, causes the page to render the suspended animation state, therefore may set the timeout $.ajax ({    timeout:2000,});
If an AJAX does not want to trigger global events, you can set a cancellation, such as canceling the trigger. Ajaxstart () and. Ajaxstop () Global events: $.ajax ({    global:false,});
Two. Error handling Ajax asynchronous commits, it is not possible that all cases are completed successfully, but also because of code asynchronous file errors, network errors cause the submission failed. At this point, we should report the error, reminding the user to resubmit or prompt the developer to fix it. In the previous high-level package there was no callback error handling, such as $.get (), $.post (), and. Load (). Therefore, the earlier method returns an error message by using the Global. Ajaxerror () event method. After jQuery1.5, you can use the Local. Error () method through concatenating processing. For the $.ajax () method, you can not only use these two methods, but also your own property method Error:function () {}.
$ ('. Ajax_btn '). On (' click ', Function () {    $.ajax ({        type: "GET",        URL: "ajax.php",        data:{            URL: " Snail ",        },        success:function (response,status,xhr) {            console.log (response);        },        error:function (Xhr,errortext,errorstatus) {            console.log (XHR);            Console.log (errorText);            Console.log (ErrorStatus);})    });
$.post () uses the concatenating. Error () method to tip the error, and the Concatenating method will be replaced by. Fail () $.post (' ajax.php '). Error (function (xhr,status,info) {    Console.log (xhr.status+ ': ' +xhr.statustext);    Console.log (status+ ': ' +info);});
$.post () uses the global. Ajaxerror () event hint error $ (document). Ajaxerror (function (event,xhr,settings,infoerror) {    alert ( xhr.status+ ': ' +xhr.statustext);    Alert (settings+ ': ' +info);});
Three. Request Global Events jquery provides many global event methods for AJAX operations, such as the. Ajaxstart (),. Ajaxstop (),. Ajaxerror (), and other event methods. They all belong to global events that are triggered at the time of the request, in addition to these, there are other global events:. Ajaxsend (), there is no corresponding local method, only the property beforesend, the function to bind before the request is sent: Ajaxcomplete (), corresponding to a local method. Complete (), after the request is completed, register a callback function: Ajaxsuccess (), corresponding to a local method of. Success (), executed when the request was completed successfully. Note: The global event method is triggered by all AJAX requests and can only be bound to the document. While the local method is for an Ajax. For some of the parameters of the global event methods, most of them are objects, which properties or methods can be called, which can be obtained through the traversal method.
Traverse the properties of the Settings object $ (document). Ajaxsuccess (function (event,xhr,settings) {for    (var i in Settings) {        Console.log (i);    }});
$.post () The local method to complete the request. Complete () $.post (). Completion (function (xhr,status) {    console.log ("Done! ");})
$.post () The global method that the request completed. Ajaxcomplete () $ (document). Ajaxcomplete (function (event,xhr,setting) {    console.log ("Done! ");})
The $.ajax () method can be set directly through the property. $.ajax ({    type: "POST",    URL: "ajax.php",    success:function (DATA,STATUS,XHR) {},    complete:function ( Xhr,status) {},    beforesend:function (xhr,settints) {}})

Note: After the jQuery1.5 version, use the. Success (),. Error (), and. Complete () concatenating methods, which can be replaced with. Done (),. Fail (), and. Always ().

Four. JSON and JSONP if the $.ajax () method is in the same domain, the JSON file can be loaded as long as the DataType property is set. In the non-identical domain, JSONP can be used, but it is also conditional. If you want to manipulate files across domains, we must use JSONP. JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags to return to the client, with cross-domain access in the form of javascriptcallback (this is simply a JSONP implementation form).
$.ajax ({    type: "GET",    dataType: "Jsonp",    success:function (DATA,STATUS,XHR) {}})
Five. Jqxhr object before we used the local method:. Success (),. complete (), and. Error (). These three local methods are not called by XMLHttpRequest objects, but are called by the objects returned by global methods such as $.ajax (). This object is the Jqxhr object, which is a superset of the native object xhr. Note: If you use the Jqxhr object, then the. Done (),. Always (), and. Fail () are recommended instead. Success (),. complete (), and. Error (). It is likely that these three methods will be scrapped in a future release. There are three advantages to using JQXHR's concatenating approach than $.ajax (): 1. Can be concatenating operation, readability greatly improved; 2. The same callback function can be executed more than once; 3. Specify a callback function for multiple operations;

Cliché Ajax

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.