Basic Learning tutorials for using jquery to process AJAX requests _jquery

Source: Internet
Author: User
Tags serialization

$.ajax Shortcut method

$.get (Url,[data],[callback],[type])
$.post (Url,[data],[callback],[type))

The two methods are requested in different ways and in the same way.
Parameter: url[request address],data[The requested data content (obj object)],callback[callback function (can only handle request success events)].
type[request returns the encoding format of the data (default contenttype specified format)]

$.get ('/test?x=1 ');
$.get ('/test ', {z:2});
$.post ('/test ', {y:2});
$.get ('/user ', function (DATA,CALLBACKTYPE,JQXHR) {
  data//returns
  the status information (string) of the data callbacktype//returned data jqxhr//
  jquery encapsulated Xhr Object
});
$ (selector). Load (Url,[data],[callback])

Load a page fragment into a selector container

$ ("#content"). Load ('/user ');
$.getjson (Url,[data],[callback])

If the JSON data callback succeeds, it fails

$.getjson ('/test ', {type:1},function () {
  console.log (argument)
});
$.getscript (Url,[claaback])

Dynamically Loading script files

$.gerscript ('/js/test.js ', function () {
  alert (test (1,2));
});

$.ajax Detailed use method

$.ajax (Url,[settings]);

$.ajax ({
  URL: '/test ',
  success:function () {
    alert (' OK ');
  }
});

callback function that handles the result of the response:
success[successful],error[request failed],
statuscode[indicates the callback function of the returned status code],
complete[callback function (handling requests to return different status codes) before the request returns

$.ajax ('/test ', {
  success:function (data) {
    console.log (arguments);
  },
  error:function (JQXHR, Textstatus,err) {
    //jqxhr:jquery enhanced XHR
    //textstatus: Request completion status
    //err: Underlying exception object thrown by throw, type and value related
    to error type Console.log (arguments);
  },
  complete:function (jqxhr,textstatus) {
    //jqxhr:jquery enhanced XHR
    // Textstatus: Request Completion Status Success | Error
    Console.log (arguments);
  },
  statuscode:function () {
    ' 403 ': function (Jqxhr,textstatus, ERR) {
      //jqxhr:jquery enhanced XHR
      //textstatus: Request completion status
      //err: Underlying exception object thrown by throw, type and value related
      to error type Console.log (arguments);
      Console.log ();
    }, ' n '
    : function () {Console.log ()}}}   
);

Requested data: Data,processdata,contenttype,traditional

$.ajax ('/test ', {
  ///Requested data content
  data:{
    a:1,
    b:2
  },
  //Request mode
  type: ' POST ',
  // Whether the requested data is transcoding (for transmitting data to the content of the HTML node)
  processdata:true,
  //whether the current data is used in the traditional way of URL encoding
  traditional:true,
  // Request data Encoding Format (
  contentType: ' Application/json '
});

Response data: Datatype,datafilter

$.ajax ('/test ', {
  success:function (data) {
    Console.log (typeof data)
  },
  //defined type
  of return data DataType: ' JSON | HTML | Text | Jsonp | Script ',
  //return the underlying raw data for preprocessing
  datafilter:function (data,type) {
    //data: Raw Data
    //type: Specified data type
  }  
});

Pre-processing: beforesend

$.ajax ('/test ', {
  beforesend:function (jqxhr,settings) {
    console.log (arguments);
    Jqxhr.setrequestheader (' Test ', ' haha ');
    Jqxhr.testdata = {A:1,b:2};
  ,
  complete:function (jqxhr) {
    console.log (jqxhr.testdata)
  }
});

Request type: Get (default) | POST | Put | DELETE
Synchronous Async: Async (Default True)
Caching: Cache (Default True)
Other parameters:
1.global[whether global events are triggered]
2.ifmodifed[load data only when server data changes]
3.username,password[http need verification time]
4.timeout[sets the request timeout time, if the request timeout triggers the error]
5.context[the object in the callback that this points to]
Other related APIs

$.ajaxsetup (option)

Set global default parameters

The default is GET request
$.ajax ('/test ');

Modify the global request method for post
$.ajaxsetup ({
  type: ' Post ',
  headers:{
    test:new Date (). GetTime
  },
  cache: False
});

The request mode changes to post
$.ajax ('/test ');
$.ajaxprefilter ([Datatypes],handler (OPTION,ORIGINALOPTIONS,JQXHR))

Pre-Request preprocessing provides an AOP (facet-oriented) programming pattern for common purposes:
1. Perform specific processing logic according to option settings
2. Modify option value change request default behavior
3. Modify default datatype by return

Example: Modifying the default datatype by return

$.ajaxprefilter (' Text HTML json ', function (OPTIONS,ORIGINALOPTIONS,JQXHR) {
  //options request parameter with default value
  // Originaloptions the parameters passed in the request, excluding the default value
  //jqxhr:jquery enhanced XHR
  console.log (arguments);
  if (Options.url = = '/test ') {return
    ' text ';
  }
});

$.ajax ('/test ', {
  type: ' Post ',
  dataType: ' text ',
  //custom property
  test: ' Haha '
});

Example: Multiple requests only last valid, avoid data confusion caused by multiple requests

var requests = {};
$.ajaxprefilter (function (OPTIONS,ORIGINALOPTIONS,JQXHR) {
  if (Requests[options.url)) {
    requests[ Options.url].abort ();
  }
  Requests[options.url] = jqxhr;
};

$.ajax ('/test/');
$.ajax ('/test/');

Example: Unified Modify Request Path

$.ajaxprefilter (function (options) {
  if (options.url.substr (0,5) = = '/usr ') {
    Options.url = Options.url.replace ('/usr/', '/user/');
    Options.header = {
      a:1
    }}}
);

$.ajax ('/usr/');

Global events

After jQuery-1.9, global events must be bound to the document

$ (document). Ajaxsuccess (Globaleventhander);
$ (document). Ajaxerror (Globaleventhander);
$ (document). Ajaxcomplete (Globaleventhander);
$ (document). Ajaxstart (Globaleventhander);
$ (document). Ajaxstop (Globaleventhander);
$ (document). Ajaxsend (Globaleventhander);
function Globaleventhander (event) {
  console.log (arguments);
  Console.log (Event.type);
}
$.ajax ('/test?err=y ');/Request successful
$.ajax ('/test?err=n ');/request failure
//Request order:
//ajaxstart >> ajaxsend >> ajaxsend >> ajaxsuccess >> ajaxcomplete >> ajaxerror >> ajaxcomplete >> ajaxstop

Serialization of

1.param[serialization of a Key/value object]
2.serialize[Create URL-encoded text strings by serializing form values]
3.serializearray[creates an array of objects (names and values) by serializing form values]

Example: param ()

var params = {a:1, b:2};
var str = $.param (params);
Console.log (str);
A=1&b=2 "

Example: Serialize ()

<form>
  <div><input type= "text" Name= "a" value= "1"/></div>
  <div><input Type= "text" name= "B" value= "2"/></div>
  <div><input type= "hidden" name= "C" value= "3"/></ div>
</form>
<script type= "Text/javascript" >
  $ (' form '). Submit (function () {
   Console.log ($ (this). Serialize ());
   A=1&b=2&c=3 return
   false;
  });
</script>

Example: Serializearray ()

<form>
  first:<input type= "text" Name= "value=" 1 "/><br/> Last
  : <input type=" Text " Name= "Last" value= "2"/><br/>
</form>
<script type= "Text/javascript" >
  $ (' form '). Click (function () {
    x=$ ("form"). Serializearray ();
    Console.log (x);
    {[Name:first,value:1],[name:last,value:2]}}
  );
</script>

Ajax-Chained Programming method
in the process of development, often encounter some time-consuming operations, such as AJAX read Server data (asynchronous operation), traversing a large array (synchronous operation). Whether asynchronous operation, or synchronous operation, in short, can not get results immediately, JS is a single-threaded voice, can not get results immediately, will be waiting (blocking).

The general practice is to use the callback function (callback), that is, the first definition of a function, the JS engine does not wait for these time-consuming operations, but continue to execute the following code, and so on, when these time-consuming operations end, back to perform the predefined function. Like the following AJAX code:

$.ajax ({
  URL: "test.html",
  success:function () {
    Console.log ("Success");
  },
  error: function () {
    console.log ("error");
  }
});

But this is not strong enough to be flexible and long-winded. To this end, the jQuery1.5 version introduces the deferred feature, providing a more powerful and flexible programming model for handling event callbacks.

$.ajax ("test.html")
. Done (
  function () {
    Console.log ("Success");
  }
)
. Fail (
  function () {
    console.log ("error");
  }
);

is not a chain call, what are the advantages?

Merit One: You can specify multiple callback functions clearly

function FnA () {...}
function FnB () {...}
$.ajax ("test.html"). Done (FnA)-Done (FnB);

Imagine, if you use the previous programming mode, you can only write this:

function FnA () {...}
function FnB () {...}
$.ajax ({
  URL: "test.html",
  success:function () {
    FnA ();
    FnB ();
  }
);

Advantage Two: Specify callback functions for multiple operations

$.when ($.ajax ("test1.html"), $.ajax ("test2.html"))
. Done (function () {Console.log ("Success");})
. Fail (function () {Console.log ("error");});

In the traditional programming mode, can only repeat success,error and so on callback.

Related Article

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.