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

Destructuring assignment in ES6

 In the past, when we wanted to assign a value to a variable, such as an array type and an object type, to assign a value to a variable, we could only specify the value directly. It is very troublesome to write in this way, but under the ES6 syntax specification, it is allowed to directly extract the required values from arrays and objects according to a certain pattern, and directly assign variables to variables. This method is called Destructuring, which is simple to understand. That is, the left and right sides of the equal sign are equal.

favicon.ico 404 Not Found Causes and Solutions

 What is favicon? It is the abbreviation of Favorites Icon. Its function is that in addition to displaying the corresponding title in the browser's favorites, icons can also be used to distinguish different websites. When I encounter this kind of error, I feel very uncomfortable. There is obviously no problem. Why is a 404 error reported? The following is the solution.