jquery Ajax Example Tutorials and some advanced usage

Source: Internet
Author: User

jquery ajax Call Mode: Jquery.ajax (url,[settings]), jquery Ajax common parameters: red flag parameters almost every AJAX request will use these parameters, this article will introduce more jquery Ajax instances, There will be some Ajax advanced usage later

Query Ajax call Mode: Jquery.ajax (url,[settings]), because the actual use of the process is often configured not many, so here is not listed all parameters, even some of the parameter defaults, is the best practice, there is no need to define their own, unless there is a special need , if you need all the parameters, you can view the jquery API

| jquery ajax Common parameters :

$.ajax ({url:"test.html",//Ajax Request AddressCachefalse,//(default: False When True,datatype is script and Jsonp) will not cache this page, we recommend using the defaultType: "GET",//the Request mode is "POST" or "get", and the default is "get". Note: other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it. DataType: "json",//These types can be optional depending on the return data type: XML HTML script JSON Jsonp text    //the data sent to the server can be passed directly to the object {a:0,b:1}, if a GET request is automatically stitched to the url, such as: &a=0&b=1    //If an array, jQuery automatically corresponds to the same name for the different values. such as {foo:["bar1", "bar2"]} is converted to "&foo=bar1&foo=bar2". data:{},//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. This is an Ajax event. If you return false, you can cancel this Ajax Request. Beforesend:function(xhr) {//this defaults to the options parameter that is passed when the AJAX request is invoked    },    //This object is used to set the context of an ajax-related callback Function. That is, let the this object in the callback function point (if This parameter is not set, then this points to the options parameter that is passed when the AJAX request is called).     //for example, You specify a DOM element as the context parameter, so that you set the success callback function to be the DOM Element. context:document.body,//callback function after the request succeedsSuccessfunction(data,textstatus) {//This is the options parameter passed when the AJAX request is invoked, and if the context is set to change this, then this is the changed    },    //This function is called when a request Fails. There are three parameters: the XMLHttpRequest object, the error message, and (optionally) the exception object that is Caught.     //If an error occurs, the error message (the second argument) may also be "timeout", "error", "notmodified", and "parsererror", in addition to being Null. Errorfunction(xmlhttprequest, textstatus, Errorthrown) {//usually among textstatus and Errorthrown        //only one will contain information        //This is the options parameter passed when the AJAX request is called    },    //the callback function after the request is completed (called after the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the successful request typeCompletefunction(xmlhttprequest, Textstatus) {//This is the options parameter passed when the AJAX request is called    },    //a set of numeric HTTP code and function objects that call the appropriate code when RESPONDING. For example, If the response status is 404, the following alerts will be triggered:statuscode:{404:function() {alert (' 404, page does not exist '); }    }});

| jquery Ajax sends a GET request with data returned as JSON

The most commonly used Ajax way to get data in combat, generally using get method

$.ajax ({    "GET",    "page.php",    dataType:' json ',    data: {id: 1001},// can also be a string link "id=1001", It is recommended to use object    function(data) {        console.log ( "data returned:" + " );}    );

|jquery Ajax sends a POST request with data returned as JSON

  The most commonly used Ajax way to submit data in combat, submit the General post method

  

$.ajax ({    "POST",    "page.php",    dataType:' json ',    data: {name: "zhang san", sex:1},// can also be a string link "name= Zhang San &sex=1", It is recommended to use object    function(data) {         // in the actual operation, the returned JSON object may have a successful error in the Judgment tag, so you may also need to determine        Console.log ("returned data:" + data );}    );
|jquery Ajax sends a GET request in shorthand mode:

In fact, the Ajax two-time package, you can control the underlying AJAX API

 

// $.get ("request url", "sent data object", "success callback", "return data type"); $.get ("test.cgi", {name: "John", time: "2pm" },   function(data) {      alert ("data Loaded: "+ data";},' json ');
|jquery Ajax sends a POST request in shorthand Mode:

In fact, the Ajax two-time package, you can control the underlying AJAX API

// $.post ("request url", "sent data object", "success callback", "return data type"); $.post ("test.cgi", {name: "John", time: "2pm" },   function(data) {      alert ("data Loaded: "+ data";},' json ');
|A tool function that jquery Ajax often uses

When Ajax submits data, it is usually submitted with a form, so it is useful to serialize the form data, such as $ ("form"). serialize ()

//Complete real example: (the form HTML structure is not written)$ ("form"). on ("submit",function(){        varURL = this. action;//action that can be taken directly to the form        varFormData = $ ( this). Serialize (); $.post (url,formdata,function(data) {//return success, can do one other thingConsole.log (data); },' JSON '); //block form default commit behavior        return false    })
|jquery Ajax requests a successful callback to be rewritten into ligatures mode. done

The success of an AJAX request is usually handled by using a callback to process the return data, but in jquery you can also use the Ligatures method instead of the callback Method. As follows:

// The argument can be a function or an array of functions. When the delay succeeds, the done function is Called. Callback execution is in the order in which they are added.  // once Deferred.done () returns a lingering object, other methods of delaying the object can also be linked here, including the add. done () Method. When deferred resolution, Web front-end development $.get ("ajax.php"). Done (function(    ) {// delay Success    alert ( "ok"). Fail (function() {    // delay failed;    Alert ("$.get failed!" );});
The jquery Ajax ligatures approach also has a two-in-one Approach. Then,.then can also write multiple, later. then you can use the results in the Previous. Then.
$.get ("test.php"). then (    function() {        // delay succeeded     },     function () {        // delay failed;     });
jquery Ajax also has a Jquery.when method

Provides a way to execute a callback function for one or more objects, which typically represents an asynchronous event. If a single delay is passed to jquery.when, it is returned by a callback function that accesses the binding through this method and other methods attached to the lingering object, such as Defered.then.
When the delay is resolved or rejected, the usual code creates the original delay, and the appropriate callback is Called. As follows:

// two all requests successfully execute callback  This API has a detailed description of $.when ($.ajax ("p1.php"), $.ajax ("p2.php") under the "tools" section of the jquery API  . Then (function() {        /// Two all requests succeeded    function() {         // any one execution failure    });

A practical example of jquery ajax, where Ajax request services are centralized into service.js

The jquery Ajax request is written as a service, such as the following code in Service.js:

//each time to repeat the AJAX code and some data processing, the global hint can be written here, of course, there is no business logic, only to do some data processing and some hintsfunctionMyService () {return{query:function(data) {var_data = data| |{}; return$.get ("test.php", _data). then (function(){//Delayed success},                    function(){//Delay failed;}                ); }, submit:function(data) {var_data = data| |{}; return$.post ("test.php", _data). then (function(){},                    function(){}                ); }    }}//of course, The code inside should be modular, rather than declaring a global myservice directly .

This article links: jquery Ajax Example Tutorials and some advanced usage http://www.51xuediannao.com/javascript/jquery_ajax.html

jquery Ajax Example Tutorials and some advanced usage

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.