Skip to main content

Native ajax usage

 What is AJAX? AJAX stands for "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications for data interaction between browsers and servers. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, which allows web pages to request small amounts of information from the server instead of the entire page. AJAX describes a web application architecture that mainly uses scripts to manipulate HTTP. The main feature of AJAX applications is to use scripts to manipulate HTTP and web servers for data exchange without causing page reloads. Simply put, without reloading the entire web page, AJAX loads data in the background and displays it on the web page, which can partially refresh the page. The user has a better experience using the web page, but cannot go back.

Here is the client code:

<style>
        #box1{
            width: 200px;
            height: 300px;
            border: 1px solid #b09;
        }
    </style>
</head>
<body>
    <div id="box1"></div>
    <button>send</button>
    <button>Cancel</button>
    <script>
        const box1=document.getElementById("box1");
        const btn=document.getElementsByTagName("button")[0];
        let xhr=null;
        let flag=false;
        //
        btn.onclick=function(){
            if(flag) xhr.abort();
            xhr=new XMLHttpRequest();
            xhr.responseType="json";
            //set timeout
            /* xhr.timeout=2000;
            xhr.ontimeout=()=>{
                alert("TimeOut....")
            }; */
            /* xhr.onerror=()=>{
                alert("Internet Error!!!");
            } */
            flag=true;
            xhr.open("POST","http://localhost:8000/server-json");
     // xhr.setRequestHeader("Content-Type","application/x-www-from-urlencoded");
            // xhr.setContentType="json";
            xhr.send("id:100&name:'aaa'");
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    flag=false;
                    if(xhr.status>=200&&xhr.status<=300){
                        /* const data=JSON.parse(xhr.response);
                        box1.innerHTML=`${data.id}===${data.namea}`; */
                        box1.innerHTML=xhr.response.id+"----"+xhr.response.namea;
                    }
                }
            }
        };
        /* const btn=document.getElementsByTagName("button")[0];
        btn.onclick=()=>{
            xhr.abort();
        } */

The following is the server code, using Node.JS:

import express, { response } from "express";
const app=express();
app.all("/server-json",(request,response)=>{
    response.setHeader("Access-Control-Allow-Origin","*");
    response.setHeader("Access-Control-Allow-Headers","*");
    const obj={id:100,namea:"aaaa699966"};
    setTimeout(()=>{
        response.send(JSON.stringify(obj));
    },3000);
});
app.listen(8000,()=>{
    console.log("server is listening。。。。");
})

5 core steps to create ajax:

  • Create an instance of XMLHttpRequest
  • open use the open method to set the interaction information with the server
  • Set the request header requestHeader (according to the sending request, set the corresponding parameters, if the requestHeader is not set by default, the plain text can be sent (when the Content-type is not specified, this is the default value)
  • Set the data sent by send() and start interacting with the server
  • If the request is completed and the response is completed, the response data is obtained


Comments

Popular posts from this blog

Use of js array filter() method

 Arrays are frequently used in development, and processing data in arrays is one of the more common and important operations. Therefore, processing data in arrays during development is an important skill. Every developer Everyone should master the operations of arrays, especially for junior developers who have just entered the industry, so be sure to master the relevant skills. This article mainly shares some operations to filter the data in the array, about the use of the filter() method.

vue routing global guard beforeEach and afterEach

 Global routing front guard (beforeEach) This function is used the most. Its function is to perform permission-related verification before routing jumps. This function contains three parameters: to: the object of the target route that is about to enter; from: the route that the current route is leaving; next: confirm the release. It can be used to log in and register, to determine whether there is a token before logging in, and release if it exists. , if it does not exist, it will not be released. The post routing guard (afterEach), its role is to trigger after the routing jump.