How to Use jQuery to process AJAX requests

Source: Internet
Author: User
This article mainly introduces the basic learning tutorial on how to use jQuery to process AJAX requests. In addition, it also introduces the method of Event Callback for chain processing. It is worth learning from the simple perspective. If you need it, you can refer to it. $. 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 ()

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.