JQuery ajax (Review)-Baidu ajax request detached Edition

Source: Internet
Author: User

You have not read the wrong title. This article is indeed About Baidu ajax, but it was a long time ago.
Because the jQuery ajax module has more than 800 lines, and the core function jQuery. ajax has more than 380 lines, directly analyzing this code can easily be confused by the Code logic.

So let's analyze a simple piece of ajax code from the early Baidu jigsaw puzzle project.
Here we will first review the ajax knowledge.

Baidu. ajax. request detached version
Copy codeThe Code is as follows:
/**
* Send an ajax request
* @ Author: allstar, erik, berg
* @ Name ajax. request
* @ Function
* @ Grammar ajax. request (url [, options])
* @ Param {string} the url of the request sent by the url
* @ Param {Object} options Option parameter for sending the request
* @ Config {String} [method] the type of request sent. The default value is GET.
* @ Config {Boolean} [async] indicates whether the request is asynchronous. The default value is true (asynchronous)
* @ Config {String} [data] The data to be sent. This attribute is not required for a GET request.
* @ Config {Object} [headers] the http request header to be set
* @ Config {number} [timeout] timeout time, in ms
* @ Config {String} [username] User Name
* @ Config {String} [password] password
* @ Config {Function} [onsuccess] function (XMLHttpRequest xhr, string responseText) triggered when the request is successful ).
* @ Config {Function} [onfailure] function (XMLHttpRequest xhr) triggered when the request fails ).
* @ Config {Function} [onbeforerequest] function (XMLHttpRequest xhr) is triggered before a request is sent ).
*
* @ Meta standard
* @ See ajax. get, ajax. post
*
* @ Returns {XMLHttpRequest} the XMLHttpRequest object that sends the request
*/
Var ajax = {};
Ajax. request = function (url, options, type ){
// Whether asynchronous
Var async = options. async | true,
// User name and password
Username = options. username | "",
Password = options. password | "",
// Data to be transmitted
Data = options. data | "",
// GET or POST
Method = (options. method | "GET"). toUpperCase (),
// Request Header
Headers = options. headers | | {},
// Event processing function table
EventHandler = {},
// Request data type
DataType = type | "string"; // xml | string
Function stateChangeHandler (){
// Check if you have prepared
If (xhr. readyState = 4 ){
// Obtain the current xhr status
Var sta = xhr. status;
// Determine whether the request is successful
If (Stas = 200 | sta = 304 ){
// If the call succeeds, the call is successful.
Fire ("success ");
} Else {
// Trigger upon failure
Fire ("failure ");
}
// Clear the binding
Window. setTimeout (function (){
Xhr. onreadystatechange = new Function ();
If (async ){
Xhr = null;
}
}, 0 );
}
}
Function fire (type ){
// Change the type to ontype
Type = "on" + type;
// Find the corresponding event handler in the event processor table
Var handler = eventHandler [type];
// If a function exists
If (handler ){
// If it fails
If (type! = "Onsuccess "){
Handler (xhr );
// Succeeded
} Else {
// Return different data based on dataType
Handler (xhr, dataType! = "Xml "? Xhr. responseText: xhr. responseXML );
}
}
}
// Assemble eventHandler
For (var key in options ){
EventHandler [key] = options [key];
}
// Create an XMLHttpRequest object
Var xhr = new XMLHttpRequest ();
// If the method is GET, assemble the data into the url
If (method = "GET "){
Url + = (url. indexOf ("? ")> = 0 )? "&":"? ";
Url + = data;
// Clear data
Data = null;
}
// Asynchronous
If (async ){
// The processor bound to readystatechange
Xhr. onreadystatechange = stateChangeHandler;
}
// Check whether a password is required.
If (username ){
Xhr. open (method, url, async, username, passowrd );
} Else {
Xhr. open (method, url, async );
}
// If it is POST
If (method = "POST "){
// Set the Request Header
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
}
// Set all request header information in options
For (var key in headers ){
Xhr. setRequestHeader (name, headers [key])
}
// Trigger the event beforerequest
Fire ("beforerequest ");
// Send data
Xhr. send (data );
// If it is not asynchronous
If (! Async ){
// Directly run stateChangeHandler to process data
StateChangeHandler ();
}
Return xhr;
}

This code is easy to understand.:
• Create an XMLHttpRequest object through XMLHttpRequest.
• Check whether it is GET or POST. If it is GET, assemble the url. If it is POST, set the request header.
• Check whether the listener is asynchronous. If so, register the listener function stateChangeHandler.
• If you do not need a user name or password, run open.
• Send a request.
• Wait for the listening function to process the event.
Baidu. ajax. get & baidu. ajax. post
Copy codeThe Code is as follows:
/**
* Send a post request
* @ Name ajax. post
* @ Function
* @ Grammar ajax. post (url, data [, onsuccess])
* @ Param {string} the url of the request sent by the url
* @ Param {string} data sent
* @ Param {Function} [onsuccess] callback function after successful request, Function (XMLHttpRequest xhr, string responseText)
* @ Meta standard
* @ See ajax. get, ajax. request
*
* @ Returns {XMLHttpRequest} the XMLHttpRequest object that sends the request
*/
Ajax. post = function (url, data, onsuccess ){
Return ajax. request (url, {"data": data, "onsuccess": onsuccess, method: "POST "});
}

Copy codeThe Code is as follows:
/**
* Send a get request
* @ Name ajax. get
* @ Function
* @ Grammar ajax. get (url [, onsuccess])
* @ Param {string} the url of the request sent by the url
* @ Param {Function} [onsuccess] callback function after successful request, Function (XMLHttpRequest xhr, string responseText)
* @ Meta standard
* @ See ajax. post, ajax. request
*
* @ Returns {XMLHttpRequest} the XMLHttpRequest object that sends the request
*/
Ajax. get = function (url, data, onsuccess ){
Return ajax. request (url, {"data": data, "onsuccess": onsuccess });
}

Both baidu. ajax. get and baidu. ajax. post are extended through baidu. ajax. request.

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.