一、AJAX Basic Concepts

1.1 What is AJAX

  • AJAX full name: Asynchronous JavaScript and XML
  • Core function: Realize asynchronous data interaction between browser and server
  • Features: It can exchange data with the server and update part of the web content without refreshing the entire page

Creation and use of XMLHttpRequest instance

// 1. Standard creation method​
const xhr = new XMLHttpRequest();​
 ​
// 2. Compatible writing method (adapting to IE5/6)​
function createXHR() {​
    if (typeof XMLHttpRequest !== "undefined") {​
        return new XMLHttpRequest();​
    } else if (typeof ActiveXObject !== "undefined") {​
        // IE6 and below​
        if (typeof arguments.callee.activeXString !== "string") {​
            const versions = [​
                "MSXML2.XMLHttp.6.0",​
                "MSXML2.XMLHttp.3.0",​
                "MSXML2.XMLHttp"​
            ];​
            for (let i = 0; i < versions.length; i++) {​
                try {​
                    new ActiveXObject(versions[i]);​
                    arguments.callee.activeXString = versions[i];​
                    break;​
                } catch(ex) {​
    }​
}

1.2 The difference between synchronous and asynchronous

Synchronous:

  • Code is executed in sequence
  • The next task can only be executed after the previous task is completed
  • May cause page blocking

Asynchronous:

  • Multiple tasks can be executed simultaneously
  • Tasks do not affect each other
  • Improve page performance and user experience
// Synchronous example​
console.log('Start');​
alert('Synchronous operation');​
console.log('End');​
 ​
// Asynchronous example​
console.log('Start');​
setTimeout(() => {​
    console.log('Asynchronous operation');​
}, 1000);​
console.log('End');

二、Detailed explanation of AJAX status codes

2.1 readyState status code

The readyState property of the XMLHttpRequest object indicates the current active phase of the request/response process:

const xhr = new XMLHttpRequest();​
xhr.onreadystatechange = function() {​
    switch(xhr.readyState) {​
        case 0: // UNSENT​
            console.log('open() method has not been called yet');​
            break;​
        case 1: // OPENED​
            console.log('open() method has been called');​
            break;​
        case 2: // HEADERS_RECEIVED​
            console.log('Response headers have been received');​
            break;​
        case 3: // LOADING​
            console.log('Receiving response body');​
            break;​
        case 4: // DONE​
            console.log('Request completed');​
            break;​
    }​
};

2.2 HTTP status codes

Common HTTP status codes and their meanings:

  • 2xx Success response
  • 200: Request successful
  • 201: Creation successful
  • 3xx Redirection
  • 301: Permanent redirect
  • 302: Temporary redirect
  • 4xx Client error
  • 400: Request syntax error
  • 404: Resource does not exist
  • 5xx Server error
  • 500: Server internal error

2.3 Properties of XHR objects

// 1. readyState - The current active phase of the request/response process​
xhr.readyState  ​
// 0: Uninitialized. The open() method has not been called yet​
// 1: Started. The open() method has been called, but the send() method has not been called​
// 2: Sent. The send() method has been called, but no response has been received yet​
// 3: Receiving. Part of the response data has been received​
// 4: Completed. All response data has been received​
 ​
// 2. status - HTTP status code​
xhr.status  // For example: 200, 404, 500, etc.​
     ​
// 3. statusText - HTTP status description​
xhr.statusText  // For example: "OK", "Not Found", etc.​
     ​
// 4. responseType - Response data type​
xhr.responseType  // "text", "json", "blob", "arraybuffer", etc.​
     ​
// 5. response - Response content​
xhr.response​
     ​
// 6. timeout - Timeout setting (milliseconds)​
xhr.timeout = 3000;

2.4 Core method usage

// 1. open() - Initialize the request​
xhr.open("GET", "url", true);  // method, url, async​
// The third parameter true indicates an asynchronous request, false indicates a synchronous request​
     ​
// 2. send() - Send the request​
xhr.send(null);  // GET request​
xhr.send(data);  // POST request to send data​
     ​
// 3. setRequestHeader() - Set request header​
xhr.setRequestHeader("Content-Type", "application/json");​
     ​
// 4. abort() - Terminate the request​
xhr.abort();

AJAX requests are asynchronous by default, but can indeed be configured to be synchronous. These two modes have their own applicable scenarios

Asynchronous requests (default)

Applicable scenarios:

  • Asynchronous requests should be used in most cases
  • Situations where user interface responsiveness needs to be maintained
  • Perform background operations without blocking user interaction
  • Multiple parallel requests need to be made simultaneously
  • Long-running operations (such as data upload, large amount of data processing)

Advantages:

  • Does not block the user interface
  • Provides a better user experience
  • Allows users to continue interacting with the page
  • Can handle multiple requests at the same time

Synchronous requests (special cases)

Applicable scenarios:

  • When subsequent code strictly depends on the request result to continue execution
  • Operations that need to be performed in a specific order
  • Loading critical configuration data, which must be completed before continuing
  • Simple scripts or prototype development that do not focus on user experience
  • Need to ensure that data has been sent to the server before logging out or unloading the page

Notes:

  • Synchronous requests will completely block the browser interface
  • Modern browsers have begun to deprecate or disable synchronous requests
  • Will lead to a poor user experience, the user interface will freeze until the request is completed

The best practice is to use asynchronous requests as much as possible, combined with callback functions, Promises, or async/await to handle the logic after the request is completed, rather than using synchronous requests. Most modern browsers no longer recommend using synchronous AJAX requests and issue warnings in the console.

2.5 Event handling

// 1. onreadystatechange - Request status change event​
xhr.onreadystatechange = function() {​
    if (xhr.readyState === 4) {​
        if (xhr.status === 200) {​
            console.log(xhr.responseText);​
        }​
    }​
};​
     ​
// 2. Other commonly used events​
xhr.onload = function() {​
    // Triggered when the request is completed​
};​
     ​
xhr.onerror = function() {​
    // Triggered when a request error occurs​
};​
     ​
xhr.ontimeout = function() {​
    // Triggered when the request times out​
};​
     ​
xhr.onabort = function() {​
    // Triggered when the request is aborted​
};​
     ​
xhr.onprogress = function(event) {​
    }​
};

2.6 Complete usage example

function ajax(options) {​
    const xhr = new XMLHttpRequest();​
    ​
    // Set timeout​
    xhr.timeout = options.timeout || 3000;​
    ​
    // Listen for status changes​
    xhr.onreadystatechange = function() {​
        if (xhr.readyState === 4) {​
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {​
                options.success && options.success(xhr.responseText);​
            } else {​
                options.error && options.error(xhr.status);​
            }​
        }​
    };​
    ​
    // Listen for errors​
    xhr.onerror = function() {​
        options.error && options.error();​
    };​
    ​
    // Listen for timeouts​
    }​
});

三、Detailed explanation of GET and POST requests

3.1 GET request characteristics

  • Used to obtain data
  • Used to obtain (fetch) data from the server
  • Parameters are passed through the URL
  • When you enter a URL in the browser address bar and press Enter, a GET request is used by default (usually for query operations)
  • Has cache
  • Solve this problem through timestamps
  • The amount of data transmitted is small
const xhr = new XMLHttpRequest();​
xhr.open('GET', 'api/data?id=123&name=test', true);​
// Solve the cache problem of GET requests​
xhr.open('GET', `api/data?t=${new Date().getTime()}`, true);​
xhr.send();

Basic format description:

  • ? – Parameters start after the question mark
  • parameter=value – Each parameter is in the format of “parameter name=parameter value”
  • & – Use the & symbol to separate multiple parameters
https://example.com/path?parameter1=value1&parameter2=value2&parameter3=value3

3.2 POST request characteristics

  • Used to submit data
  • Parameters are passed through the request body
  • Used to send data to the server for creation or update operations, often used in form submission scenarios
  • No cache
  • Can transmit large amounts of data
const xhr = new XMLHttpRequest();​
xhr.open('POST', 'api/data', true);​
xhr.setRequestHeader('Content-Type', 'application/json');​
xhr.send(JSON.stringify({id: 123, name: 'test'}));

AJAX requests mainly use HTTP request methods, and there are only 9 standard request methods defined by the HTTP protocol

  • GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, CONNECT, TRACE

6 common request methods:

  • GET – Used to obtain data from the server, parameters are usually appended to the URL
  • POST – Used to send data to the server to create or update resources, data is included in the request body
  • PUT – Used to update existing resources on the server, send complete resource data
  • DELETE – Used to delete specified resources on the server
  • PATCH – Used to partially update resources, only send the parts that need to be modified
  • HEAD – Similar to GET request but only requests header information, does not return the response body

The specific request method to use is determined by the backend, and the backend will write an interface document for the frontend

四、Interface (API) concept

An interface is a URL address that only returns data without an interface, called API (Application Programming Interface) in English

Any URL that can display data on the page when entered is an interface address, referred to as an interface

Copy it to the browser address bar and press Enter to view the interface data

五、API interface document example

A standard interface document should have the following contents

Basic InformationDescription
Interface NameUser Login
Interface DescriptionUsers authenticate through account and password
Interface URL/api/v1/user/login
Request MethodPOST
DeveloperZhang San
Creation Time2024-02-22
Update Time2024-02-22
Request HeadersWhether Required
Content-Type
Authorization
x-client-id
Request Parameters (Request Body)Type
username
password
captcha
remember
Response Parameters (Response)Type
code
message
data.userId
data.username
data.token
data.permissions
Response Status CodesDescription
200
400
401
403
500

5.1 Request example

Parameters required by the backend interface

{​
    "username": "zhangsan",​
    "password": "e10adc3949ba59abbe56e057f20f883e",​
    "captcha": "a1b2c",​
    "remember": true​
}

5.2 Response example

Data returned by the backend

{​
    "code": 200,​
    "message": "Login successful",​
    "data": {​
        "userId": "12345",​
        "username": "Zhang San",​
        "token": "eyJhbGciOi...",​
        "permissions": ["user:read", "user:write"]​
    }​
}

5.2 Failed response example

The interface failed to request for some reason

{​
    "code": 401,​
    "message": "Incorrect username or password",​
    "data": null​
}
Supplementary InstructionsContent
Request RestrictionsInterface call frequency: 10 times/minute
Security RequirementsPassword must be MD5 encrypted, HTTPS must be used
Special InstructionsToken validity period is 2 hours
Modification Records
Modifier
Modification Time
Modification Content

Summary of AJAX and interface document knowledge

Core knowledge points review

  • Three core aspects of AJAX
  • Creation and use of XMLHttpRequest objects
  • Differences and application scenarios between GET/POST requests
  • Asynchronous processing mechanism and status code judgment
  • Key points of interface specifications
  • Standard interface document structure (basic information, request parameters, response format)
  • Interface security considerations (request headers, authentication methods)
  • Error handling mechanism

Practical application suggestions

  • Development practice
  • It is recommended to encapsulate a unified processing function for AJAX requests
  • Make good use of Promises to handle asynchronous requests
  • Use GET/POST reasonably: use GET for queries, use POST for submissions
  • Document specifications
  • Use a unified document template
  • Keep documents updated in a timely manner
  • Example code must be complete and usable

Key precautions

  • Notes on AJAX use
  • Handle cross-domain issues properly
  • Pay attention to the cache problem of GET requests
  • Exception handling cannot be omitted
  • Interface document maintenance
  • Parameter descriptions should be clear and complete
  • Update interface changes in a timely manner
  • Do a good job in version control

Learning suggestions

  • Write more demos to deepen understanding
  • Pay attention to accumulating experience in actual projects
  • It is recommended to use mature request libraries (such as Axios)
  • Be proficient in using interface document tools (such as Swagger)

By mastering AJAX and the writing of standardized interface documents, we can better conduct front-end and back-end collaboration and improve development efficiency. In actual work, we should pay attention to practice and accumulation, and constantly improve our professional abilities.

From native AJAX to Axios

Knowledge connection description

  • Learning path
  • Learning native AJAX is to understand the underlying principles
  • Axios is an encapsulation and optimization based on AJAX
  • Axios is recommended for actual development
  • Advantages of Axios
  • More concise API design
  • Automatically convert JSON data
  • Client support for defending against XSRF
  • Request and response interceptors
  • Better exception handling mechanism

Official website description

  • Create XMLHttpRequests from the browser
  • Create http requests from node.js
  • Support Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel requests
  • Automatically convert JSON data
  • Client support for defending against XSRF

Practical development suggestions

// Native AJAX writing method (learn to understand the principle)​
const xhr = new XMLHttpRequest();​
xhr.open('GET', '/api/users');​
xhr.onreadystatechange = function() {​
    if(xhr.readyState === 4 && xhr.status === 200) {​
        console.log(xhr.responseText);​
    }​
};​
xhr.send();​
 ​
// Axios writing method (used in actual development)​
axios.get('/api/users')​
    .then(response => console.log(response.data))​
    .catch(error => console.log(error));

Learning suggestions

  • First master the AJAX principle and understand the nature of asynchronous requests
  • Then learn Axios to improve development efficiency
  • Use Axios in actual projects, and trace back to the AJAX level to solve problems when encountering them

Learning native AJAX is to understand the principles, but in actual work, mature HTTP client libraries such as Axios are the first choice.

Avatar

By BytePilot

Because sharing makes us better. Let’s learn, build, and grow — one byte at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *