search
HomeWeb Front-endJS TutorialNative JS encapsulation of AJAX methods

Native JS encapsulation of AJAX methods

May 05, 2020 am 09:52 AM
ajaxjsencapsulation

Ajax is used by everyone every day. The jquery library's encapsulation of Ajax is also very complete and easy to use. Let's take a look at its internal principles and manually encapsulate an Ajax library of our own.

1. Principle

Sending native Ajax requires four steps:

1) Create Ajax object: XMLHttpRequest

2) Set request parameters: open(request parameters [get/post], url address, asynchronous or not [true/false] )

3) Set callback function: onreadystateChange is used to process the returned data

4) Send a request: send()

//TODO step1: 创建ajax对象
var xhr = new XMLHttpRequest();
//TODO step2: 设置请求参数
xhr.open('get','01.php',true);
//TODO step3: 设置回调
xhr.onreadystatechange = function () {
    //接收返回数据
    console.log(xhr.responseText);//responseText 用于接收后台响应的文本
}
//TODO step4: 发送请求
xhr.send();

2. Encapsulation

The core idea of ​​encapsulation is to treat the parts that need to be dynamically changed as parameters, and leave the unchanged parts There, in the above code, the request method (get, post), request address url, request parameter data, successful callback success, failed callback error, etc., these parameters are dynamically changed; while creating the Ajax object XMLHttprequest, event monitoring onreadystatechange, etc. are fixed, so the first step is to determine the encapsulation parameters:

v url request address

v data request data

v type request type

v success success callback

v error failure callback

v beforeSend is called before sending return false to prevent sending

v complete callback for ajax request success, no matter when Will be executed

function ajax(option){
    //用户配置option 默认配置init
    var init = {
        type:'get',
        async:true,
        url:'',
        success: function () { },
        error: function () { },
        data:{},
        beforeSend: function () {
            console.log('发送前...');
            return false;
        }
    };
    //TODO step1: 合并参数
    for(k in option){
        init[k] = option[k];
    }
    //TODO step2: 参数转换
    var params = '';
    for(k in init.data){
        params += '&'+k+'='+init.data[k];
    }
    var xhr = new XMLHttpRequest();
    // type url
    //TODO step3: 区分get和post,进行传参
    var url = init.url+'?__='+new Date().getTime();
    //TODO step4: 发送前
    var flag = init.beforeSend();
    if(!flag){
        return;
    }
    if(init.type.toLowerCase() == 'get'){
        url += params;
        xhr.open(init.type,url,init.async);
        xhr.send();
    }else{
        xhr.open(init.type,url,init.async);
      xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        xhr.send(params.substr(1));
    }
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                init.success(xhr.responseText);
            }else{
                //error
                init.error();
            }
        }
    }
}

What we should pay attention to here is that the parameter passing methods of get and post are different. The get request needs to be directly spliced ​​after the url address, and the post request needs to pass parameters in the send method, and this needs to be The request header is setRequestHeader('content-type','application/x-www-form-urlencoded'), so it needs to be distinguished when encapsulating.

Due to too many parameters, users do not need to pass in many parameters every time, otherwise it will be very cumbersome to use. Therefore, we adopt the form of default parameters. If the user does not pass in the parameter, the default value will be used. If the user does not pass in the parameter, the user's parameter will be used.

3. Usage examples

ajax({
    url: 'test.json',
    data:{test:123,age:456},
    //type:'post',
    success: function (res) {
        console.log(res);
    }
});

The above is the detailed content of Native JS encapsulation of AJAX methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:zhihu. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.