Home Web Front-end JS Tutorial jQuery ajax (review)—Baidu ajax request separated version_javascript skills

jQuery ajax (review)—Baidu ajax request separated version_javascript skills

May 16, 2016 pm 05:42 PM
ajax request

You read the title correctly. This article is indeed about Baidu ajax, but it is a version from a long, long time ago.
Since the jQuery ajax module has 800 lines, and the core function jQuery.ajax has 380 lines, it is easy to get confused by the code logic when directly analyzing this code.

So let’s first analyze a simple ajax code from the early Baidu Tangram project.
Use this to review the knowledge of ajax first.

baidu.ajax.request separated version

Copy code The code is as follows:

/**
* Send an ajax request
* @author: allstar, erik, berg
* @name ajax.request
* @function
* @grammar ajax.request(url[, options] )
* @param {string} url The url to send the request
* @param {Object} options The option parameters to send the request
* @config {String} [method] The type of request sent. The default is GET
* @config {Boolean} [async] Whether to request asynchronously. The default is true (asynchronous)
* @config {String} [data] The data to be sent. If it is a GET request, this attribute is not needed
* @config {Object} [headers] http request header to be set
* @config {number} [timeout] Timeout, unit ms
* @ config {String} [username] Username
* @config {String} [password] Password
* @config {Function} [onsuccess] Triggered when the request is successful, function(XMLHttpRequest xhr, string responseText).
* @config {Function} [onfailure] Triggered when the request fails, function(XMLHttpRequest xhr).
* @config {Function} [onbeforerequest] Triggered before sending the request, function(XMLHttpRequest xhr).
*
* @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 is needed
var async = options.async||true,
// Username, password
username = options.username||"",
password = options.password||"",
/ / Data to be transmitted
data = options.data||"",
// GET or POST
method = (options.method||"GET").toUpperCase(),
/ / Request headers
headers = options.headers||{},
// Event handler function table
eventHandler = {},
// Request data type
dataType = type||" string";//xml||string
function stateChangeHandler(){
// See if it is ready
if(xhr.readyState == 4){
// Get xhr current Status
var sta = xhr.status;
// Determine whether it is successful
if(sta == 200||sta == 304){
// If successful, trigger success
fire( "success");
}else{
// Failure triggers failure
fire("failure");
}
// Clear binding
window.setTimeout(function (){
xhr.onreadystatechange= new Function();
if (async){
xhr = null;
}
},0);
}
}
function fire(type){
// Change type to ontype
type = "on" type;
// Find the corresponding event processing function in the event handler table
var handler = eventHandler[type];
// If the function exists, then
if(handler){
// If unsuccessful
if(type != "onsuccess"){
handler (xhr);
// Successful
}else{
// Return different data according to dataType
handler(xhr,dataType!="xml"?xhr.responseText:xhr.responseXML );
}
}
}
// Assemble eventHandler
for(var key in options){
eventHandler[key] = options[key];
}
// Create a new 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;
}
// If it is asynchronous
if (async){
// Bind readystatechange handler
xhr.onreadystatechange = stateChangeHandler;
}
// See if 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 the request header information in options
for(var key in headers){
xhr.setRequestHeader(name,headers[ key])
}
// Trigger event beforerequest
fire("beforerequest");
// Send data
xhr.send(data);
// If not asynchronous
if (!async){
// Directly run stateChangeHandler to process the data
stateChangeHandler();
}
return xhr;
}

This code is relatively easy to understand:
• Create a new 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 it is asynchronous, and if so, register the listening function stateChangeHandler.
•Check if a username and password are required and execute open.
•Send a request.
•Wait for the listening function to handle the event.
baidu.ajax.get & baidu.ajax.post
Copy code The code is as follows:

/**
* Send a post request
* @name ajax.post
* @function
* @grammar ajax.post(url, data[, onsuccess])
* @param {string} url The URL address of the request
* @param {string} data The data sent
* @param {Function} [onsuccess] The callback function after the request is successful, 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 code The code is as follows:

/**
* Send a get request
* @name ajax.get
* @function
* @grammar ajax.get(url[, onsuccess])
* @param {string} url send Requested url address
* @param {Function} [onsuccess] The callback function after the request is successful, function(XMLHttpRequest xhr, string responseText)
* @meta standard
* @see ajax.post,ajax. request
*
* @returns {XMLHttpRequest} Send the requested XMLHttpRequest object
*/
ajax.get = function(url,data,onsuccess){
return ajax.request(url,{"data":data,"onsuccess": onsuccess});
}

baidu.ajax.get and baidu.ajax.post are both extended through baidu.ajax.request.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

What is the Request object in PHP? What is the Request object in PHP? Feb 27, 2024 pm 09:06 PM

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles