Define your own ajax function using JavaScript

Define your own ajax function using JavaScript

Since the network requests initiated by native js are submitted to the server in the form of query strings, it is more convenient for users to submit parameters in the form of objects, so it is necessary to process the parameter objects passed by the user, define the resolveData function, set the formal parameters to receive the parameters, traverse the objects inside, concatenate the keys and values ​​using the = method, and then add the obtained values ​​to the empty array; finally, use the & symbol to split each item of the array and return it; define the itheima function, set the formal parameters to receive the configuration object parameters passed by the user, create an xhr object, pass the passed parameters to the function that processes the parameters, and give the returned value to a variable. Since they are different requests, judgments must be made. First, it is a GET request to determine whether the method in the parameters is all equal to GET. Since the passed parameters may be lowercase, they are converted to uppercase through the toUpperCase method. If the condition is met, call the open method, fill in the corresponding values, and call the send function; POST is the same, except that the submitted data has more parameters and the POST request requires the "Content-Type" header to specify the MIME type of the request subject. Finally, call the listening event;

function resolveData(data) {
    var arr = [];
    for (var k in data) {
        var str = k + "=" + data[k];
        arr.push(str)
    }
    return arr.join("&")
}
function itheima(options) {
    var xhr = new XMLHttpRequest();
    var qs = resolveData(options.data);
    if (options.method.toUpperCase() === "GET") {
        xhr.open(options.method, options.url + "?" + qs);
        xhr.send();
    } else if(options.method.toUpperCase() === "POST"){
        xhr.open(options.method, options.url)
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        xhr.send(qs)
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var result = JSON.parse(xhr.responseText)
            options.success(result);
        }
    }
}

Finally, test whether it is successful~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test interface</title>
<script src="itheima.js"></script>
</head>
<body>
    <script>
        itheima({
            method:"GET",
            url:"http://www.liulongbin.top:3006/api/getbooks",
            data:{
                id:1
            },
            success:function(res){
                console.log(res);
            }
        });
    </script>
</body>
</html> 

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Summary of how to use ajax to set and get custom header information in js
  • How to implement ajax call background definition method based on JavaScript
  • ASP.NET MVC uses AJAX to call the JsonResult method and return custom error information
  • Detailed explanation of JavaScript custom functions
  • JavaScript recursive function definition and usage example analysis
  • Summary of several common methods of defining functions in JS
  • Detailed Example of JavaScript Function Definition Method

<<:  Flex layout makes adaptive pages (syntax and examples)

>>:  The difference between html, xhtml and xml

Blog    

Recommend

Testing of hyperlink opening target

The target attribute of a link determines where th...

Semantics: Is Html/Xhtml really standards-compliant?

<br />Original text: http://jorux.com/archiv...

UDP DUP timeout UPD port status detection code example

I have written an example before, a simple UDP se...

Use iframe to display weather effects on web pages

CSS: Copy code The code is as follows: *{margin:0;...

How to specify parameter variables externally in docker

This article mainly introduces how to specify par...

Let's talk briefly about the changes in setup in vue3.0 sfc

Table of contents Preface Standard sfc writing me...

Some basic instructions of docker

Table of contents Some basic instructions 1. Chec...

A solution to a bug in IE6 with jquery-multiselect

When using jquery-multiselect (a control that tra...

Detailed explanation of MySQL redo log (redo log) and rollback log (undo logo)

Preface: The previous article described several c...

Do you know why vue data is a function?

Official website explanation: When a component is...

A Different Kind of "Cancel" Button

The “Cancel” button is not part of the necessary ...

Detailed explanation of building MySQL master-slave environment with Docker

Preface This article records how I use docker-com...

Detailed explanation of pure SQL statement method based on JPQL

JPQL stands for Java Persistence Query Language. ...

Examples of common Nginx misconfigurations

Table of contents Missing root location Off-By-Sl...