Basic Learning tutorial for processing AJAX requests using jQuery, jqueryajax

Source: Internet
Author: User

Basic Learning tutorial for processing AJAX requests using jQuery, jqueryajax

$. Ajax shortcut

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

The two methods have different request methods, and the other methods are the same.
Parameter: url [request address], data [requested data content (obj object)], callback [callback function (only request success events can be processed)],
Type [encoding format of the data returned by the request (the default ContentType specifies the format)]

$. Get ('/test? X = 1'); $. get ('/test', {z: 2}); $. post ('/test', {y: 2}); $. get ('/user', function (data, callbacktype, jqXHR) {data // return data callbacktype // return data status information (string) jqXHR // jQuery-encapsulated XHR object}); $ (selector ). load (url, [data], [callback])

Load the page fragment into the selector container

$("#content").load('/user');$.getJSON(url,[data],[callback])

If the callback is for JSON data, the callback succeeds. Otherwise, the callback fails.

$.getJSON('/test',{type:1},function(){  console.log(argument)});$.getScript(url,[claaback])

Dynamic Loading of script files

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

$. Ajax detailed usage

$.ajax(url,[settings]);$.ajax({  url:'/test',  success:function(){    alert('ok');  }});

Callback Function for processing response results:
Success [successful], error [request failed],
StatusCode [specifies the callback function for the returned status code],
Complete [the callback function before the request is returned (processing requests that return different status codes)]

$. Ajax ('/test', {success: function (data) {console. log (arguments) ;}, error: function (jqXHR, textStatus, err) {// jqXHR: jQuery-enhanced XHR // textStatus: request Completion status // err: the exception object thrown by throw at the underlying layer. The type and value are related to the error type console. log (arguments) ;}, complete: function (jqXHR, textStatus) {// jqXHR: jQuery-enhanced XHR // textStatus: request Completion status success | error console. log (arguments) ;}, statusCode: function () {'000000': function (jqXHR, textStatus, err) {// jqXHR: jQuery-enhanced XHR // textStatus: request completion status // err: The exception object thrown by throw at the underlying layer. The type and value are related to the error type console. log (arguments); console. log (400) ;}, '000000': function () {console. log (400 );}}});

Requested data: data, processData, contentType, traditional

$. Ajax ('/test', {// request data content data: {a: 1, B: 2}, // Request Method type: 'post ', // whether to transcode the requested data (used to transmit the data as html node content) processData: true, // whether the current data uses the traditional url encoding traditional: true, // request data encoding format contentType: 'application/json '});

Response Data: dataType, dataFilter

$. Ajax ('/test', {success: function (data) {console. log (typeof data)}, // defines the type of returned data dataType: 'json | html | text | jsonp | script', // returns 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 asynchronous: async (true by default)
Cache: cache (true by default)
Other parameters:
1. global [whether to trigger a global event]
2. ifModifed [load data only when server data changes]
3. username, password [http verification required]
4. timeout [set the request timeout time. If the request timeout triggers an error]
5. context [the object this points to in the callback]
Other related APIs

$. AjaxSetup (option)

Set global default parameters

// The default value is get request $. ajax ('/test'); // modify the global request method to post $. ajaxSetup ({type: 'post', headers: {test: new Date (). getTime}, cache: false}); // The Request Method is changed to post $. ajax ('/test'); $. ajaxPrefilter ([dataTypes], handler (option, originalOptions, jqXHR ))

Pre-processing before request initiation provides an AOP (Aspect-Oriented) programming mode for common purposes:
1. Execute specific processing logic according to option settings
2. Modify the option value to change the default request Behavior
3. Modify the default ype through return

For example, use return to modify the default ype.

$. AjaxPrefilter ('text html json', function (options, originalOptions, jqXHR) {// options request parameters, including the default value // originalOptions parameters passed in the request, excluding the default value // jqXHR: XHR console enhanced by jQuery. log (arguments); if (options. url = '/test') {return 'text' ;}}); $. ajax ('/test', {type: 'post', dataType: 'text', // custom property test: 'hahaha '});

For example, multiple requests are valid only for the last time, avoiding 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/');

For example, modify the Request Path in a unified manner.

$.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 the 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'); // The request is successful $. ajax ('/test? Err = n'); // request failed // Request order: // ajaxStart> ajaxSend> ajaxSuccess> ajaxComplete> ajaxError> ajaxComplete> ajaxStop

Serialization

1. param [serialize a key/value object]
2. serialize [Create a URL-encoded text string by serializing the form value]
3. serializeArray [Create an object array (name and value) 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="First" 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
Some time-consuming operations are often encountered during the development process. For example, ajax reads server data (asynchronous operations) and traverses a large array (synchronous operations ). Regardless of asynchronous or synchronous operations, JS cannot get results immediately. JS is a single-threaded voice. If it cannot get results immediately, it will always wait (blocking ).

The general practice is to use the callback function (callback), that is, to define a function in advance, the JS engine does not wait for these time-consuming operations, but continues to execute the following code. After these time-consuming operations are completed, come back and execute the previously defined function. The following ajax code:

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

However, this writing method is not powerful and flexible enough, and it is also awkward. Therefore, the Deferred function is introduced in jQuery1.5 to provide a more powerful and flexible programming mode for Event Callback processing.

$.ajax("test.html").done(  function(){    console.log("success");  }).fail(  function(){    console.log("error");  });

It's not just a chain call. What are the advantages?

Advantage 1: Multiple callback functions can be clearly specified.

function fnA(){...}function fnB(){...}$.ajax("test.html").done(fnA).done(fnB);

Think about it. If you use the previous programming mode, you can only write it like this:

function fnA(){...}function fnB(){...}$.ajax({  url: "test.html",  success: function(){    fnA();    fnB();  }});

Advantage 2: specify a callback function 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, you can only repeat success, error, and other callbacks.

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.