JQuery Ajax Full parsing

Source: Internet
Author: User
Tags getscript browser cache

JQuery Ajax Full parsing

This article address: jQuery Ajax Full analysis

This article Qleelulu

Reprint please indicate the source!

jquery is really a very good lightweight JS framework that can help us to develop JS applications quickly and to some extent change the way we write JavaScript code.

Talk less, go straight to the point, we first look at some simple methods, these methods are to Jquery.ajax () encapsulation to facilitate our use of the method, of course, if you want to deal with complex logic, still need to use Jquery.ajax () (which will be said later).

1. Load(URL, [data], [callback]): Load the remote HTML file code and insert it into the DOM.

URL (String): The URL address of the requested HTML page.

Data (MAP): (optional parameter) Key/value data sent to the server.

Callback (Callback): (optional parameter) callback function when the request is complete (not required to be success).

This method is passed by default using GET, and is automatically converted to post if the [data] parameter is passed in. In JQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted in the DOM. Syntax such as "URL #some > selector".

This method makes it easy to dynamically load some HTML files, such as forms.

Example code:

$ (". Ajax.load"). Load ("http://www.cnblogs.com/QLeelulu/archive/2008/03/30/1130270.html. Post", Function ( ResponseText, Textstatus, XMLHttpRequest) {this;//Here This is pointing to the current DOM object, which is $ (". Ajax.load") [0]//alert (ResponseText);// Request returned content//alert (textstatus);//Request Status: Success,error//alert (XMLHttpRequest);//xmlhttprequest object});

The results are displayed here.

Note: do not know why URL write absolute path under FF will error, know the trouble to tell under. The Get () and post () examples below use an absolute path, so you will get an error under FF and you will not see the results returned. The Get () and post () examples are all cross-domain calls, and there is no way to get the results after the transmission, so the run button is removed.

2. Jquery.get(URL, [data], [callback]): Use Get method to make asynchronous request

Parameters:

URL (String): The URL address of the sending request.

Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair, will be appended to the request URL as querystring.

Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).

This is a simple GET request feature to replace complex $.ajax. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example code:

$.get ("./ajax.aspx", {Action: "Get", Name: "Lulu"}, function (data, textstatus) {///The data returned can be xmldoc, jsonobj, HTML, text, And so on. this; Here this point is the option configuration information for the AJAX request, please refer to alert (data),//alert (Textstatus),//Request status: Success,error, etc.
Of course, the error is not caught here, because the error does not run the callback function at all//alert (this);});

Click Send Request:

The This in the Jquery.get () callback function points to the option configuration information for the AJAX request:

3. Jquery.post(URL, [data], [callback], [type]): Use post to make asynchronous requests

Parameters:

URL (String): The URL address of the sending request.

Data (MAP): (optional) data to be sent to the server, expressed as a Key/value key-value pair.

Callback (function): (optional) The callback function when loading succeeds (the method is called only if the return state of response is success).

type (String): (optional) The official description is: Type of data to be sent. The type that should actually be requested for the client (Json,xml, etc.)

This is a simple POST request function to replace the complex $.ajax. The callback function can be called when the request succeeds. If you need to execute the function on error, use $.ajax. Example code:

Ajax.aspx:

Response.ContentType = "Application/json"; Response.Write ("{result: '" + request["Name"] + "Hello! (The message comes from the server) '} ');
JQuery Code:
$.post ("Ajax.aspx", {Action: "Post", Name: "Lulu"},function (data, textstatus) {//data can be xmldoc, jsonobj, HTML, text, And so on.//this; For the option configuration information for this Ajax request, refer to Jquery.get () Thisalert (Data.result);}, "JSON");

Click Submit:

The format of the request is "JSON":

If you set the request format to "JSON", at this point you do not have to set Response back ContentType: Response.ContentType = "Application/json"; Then you will not be able to capture the returned data.

Note that alert (data.result); Because the Accept header is set to "JSON", the data returned here is an object and does not need to be converted to an object using eval ().

4. Jquery.getscript(URL, [callback]): Request to load and execute a JavaScript file via GET mode.

parameters

URL (String): The JS file address to be loaded.

Callback (function): (optional) The post-load callback function is successfully loaded.

Before the JQuery 1.2 version, GetScript can only invoke the same domain JS file. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you join the script through GetScript, add the delay function.

This method can be used for example, when only the editor focus () to load the editor needs the JS file. Here are some sample code:

Load and execute the test.js.

JQuery Code:

$.getscript ("Test.js");

Load and execute ajaxevent.js, and display the information after success.

JQuery Code:

$.getscript ("Ajaxevent.js", function () {alert ("Ajaxevent.js") completes and executes. Do you click the Get or Post button above to see what's different? ");});

After loading, please re-click on the load request above to see what is different.

JQuery Ajax Events

Ajax requests generate a number of different events, and we can subscribe to these events and handle our logic in them. There are two types of Ajax events in jquery: Local events and global events.

A local event is defined within a method every time an AJAX request is requested, for example:

$.ajax ({   beforesend:function () {     ///Handle the Beforesend event   },   complete:function () {     // Handle the Complete Event   }   //...});

The global event is triggered every time an AJAX request is made, it broadcasts to all elements in the DOM, and the script loaded in the GetScript () example above is the global Ajax event. Global events can be defined as follows:

$ ("#loading"). Bind ("Ajaxsend", function () {   $ (this). Show ();}). Bind ("Ajaxcomplete", function () {   $ (this). Hide ();});

Or:

$ ("#loading"). Ajaxstart (function () {   

We can disable global events on a specific request, as long as you set the global option:

$.ajax ({   URL: "test.html",   global:false,//disables global Ajax events.   ) // ... });

The following is a complete list of Ajax events that are officially given by jquery:

  • Ajaxstart(Global Event)
    This event was broadcast if an AJAX request was started and no other AJAX requests was currently running.
    • Beforesend (Local Event)
      This event, which was triggered before an Ajax request was started, allows you to modify the XMLHttpRequest object (setting Additional headers, if need be.)
    • Ajaxsend (Global Event)
      This global event is also triggered before, the request is run.
    • Success (Local Event)
      This event is a called if the request was successful (no errors from the server, no errors with the data).
    • ajaxsuccess (Global Event)
      This event is also only called if the request was successful.
    • Error (Local Event)
      This event was only called if an error occurred with the request (you can never has both an error and a success callback W ith a request).
    • Ajaxerror (Global Event)
      This global event behaves the same as the local error event.
    • Complete (Local Event)
      This event is a called regardless of if the request was successful, or not. You'll always receive a complete callback, even for synchronous requests.
    • Ajaxcomplete (Global Event)
      This event behaves the same as the complete event and would be triggered every time an Ajax request finishes.
  • Ajaxstop(Global Event)
    This global event was triggered if there is no more Ajax requests being processed.

    Refer to the API documentation for specific global events.
    Well, here's how the most powerful Ajax request method in jquery is $.ajax ();

    Jquery.ajax (options): Loading remote data over HTTP requests

    This is the underlying AJAX implementation of jquery. Easy to use high-level implementation see $.get, $.post and so on.

    $.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to terminate the request manually.

    Note: If you specify the DataType option, make sure that the server returns the correct MIME information (such as XML returns "Text/xml"). The wrong MIME type can cause unpredictable errors. See Specifying the Data Type for AJAX requests.
    When you set the datatype type to ' script ', all the remote (not in the same domain) post requests are converted back to get mode.

    $.ajax () has only one parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options are shown below.

    In JQuery 1.2, you can load JSON data across domains and set the data type to JSONP when used. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function. When the data type is set to "Jsonp", JQuery automatically calls the callback function. (I don't quite understand that)

    Parameter list:

    Name of parameter Type Describe
    Url String (Default: Current page address) sends the requested address.
    Type String (Default: "Get") The Request method ("POST" or "get"), the default is "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
    Timeout Number Sets the request time-out (in milliseconds). This setting overrides the global settings.
    Async Boolean (default: TRUE) by default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync request will lock the browser, and the user's other actions must wait for the request to complete before it can be executed.
    Beforesend Function You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.
    function (XMLHttpRequest) {this  ;//The options for this AJAX request}
    Cache Boolean (default: TRUE) JQuery 1.2 new feature, set to False will not load the request information from the browser cache.
    Complete Function The callback function after the request completes (called when the request succeeds or fails). Parameters: XMLHttpRequest Object, Success information string.
    function (XMLHttpRequest, textstatus) {this  ;//The options for this AJAX request}
    ContentType String (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default values are suitable for most applications.
    Data Object,
    String
    Data sent to the server. is automatically converted to the request string format. The GET request will be appended to the URL. View the ProcessData option description to disallow this automatic conversion. Must be a key/value format. If an array, JQuery automatically corresponds to the same name for the different values. such as {foo:["bar1", "Bar2"]} converted to ' &foo=bar1&foo=bar2 '.
    DataType String

    Expected data type 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, with the available values:

    "XML": Returns an XML document that can be processed with jQuery.

    HTML: Returns plain text HTML information, including the script element.

    "Script": Returns plain text JavaScript code. Results are not automatically cached.

    "JSON": Returns the JSON data.

    "JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.

    Error Function (Default: This method is called when a request for automatic judgment (XML or HTML) fails.) This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being captured.
    function (XMLHttpRequest, textstatus, Errorthrown) {  //normally textstatus and Errorthown only one has the value of this   ; Options for this AJAX request}
    Global Boolean (default: TRUE) whether to trigger global AJAX events. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events
    Ifmodified Boolean (default: false) to get new data only when the server data changes. Use the HTTP packet last-modified header information to determine.
    ProcessData Boolean (default: TRUE) by default, the sent data is converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Set to False if you want to send DOM tree information or other information that you do not want to convert.
    Success Function The callback function after the request succeeds. This method has two parameters: the server returns data, returns the status
    function (data, textstatus) {  //data could be xmldoc, jsonobj, HTML, text, etc ...  This The options for this AJAX request}

    Here are a few Ajax event parameters:beforesend ,success , complete, error. We can define these events to handle each of our AJAX requests well. Note that the this in these AJAX events is the option information that points to the Ajax request (refer to the picture of this for the Get () method).
    Please read the above parameter list carefully, if you want to use jquery for Ajax development, then these parameters you must be familiar with.

    Sample code to get the blog home page of the article title:
    $.ajax ({type: "Get", url: "Http://www.cnblogs.com/rss", Beforesend:function (XMLHttpRequest) {//showloading ();}, Success:function (data, Textstatus) {$ (". Ajax.ajaxresult"). HTML (""); $ ("item", data). Each (function (i, Domele) {$ (". Ajax.ajaxresult "). Append (" <li> "+$ (Domele). Children (" title "). Text () +" </li> ");});},complete:function (XMLHttpRequest, Textstatus) {//hideloading ();},error:function () {//Request error handling}});

    A list of the first page articles is displayed here.

    Other

    Jquery.ajaxsetup (options): Set global AJAX default options.

    Set the default address of the AJAX request to "/xmlhttp/", prohibit triggering of global Ajax events, use POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters.

    JQuery Code:

    $.ajaxsetup ({  URL: "/xmlhttp/",  global:false,  type: "POST"}); $.ajax ({data:mydata});

    Serialize () and Serializearray ()

    Serialize (): The table contents of the sequence table are strings.

    Serializearray (): Serializes a tabular element (similar to the '. Serialize () ' method) to return the JSON data structure.

    Example:

    HTML code:

    <p id= "Results" ><b>results: </b> </p><form>  <select name= "single" >    <option>Single</option>    <option>Single2</option>  </select>  < Select Name= "multiple" multiple= "multiple" >    <option selected= "selected" >Multiple</option>    <option>Multiple2</option>    <option selected= "selected" >Multiple3</option>  </ select><br/>  <input type= "checkbox" name= "Check" value= "Check1"/> check1 <input type=  " CheckBox "Name=" Check "value=" Check2 "checked=" checked "/> check2 <input  type=" Radio "name=" Radio "value=" Radio1 "checked=" checked "/> Radio1  

    Serializearray () The result is:

JQuery Ajax Full parsing

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.