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

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.

Js uses recursive way to traverse the dom tree to dynamically create element nodes

 What is a dom tree? In short, DOM is the Document Object Model, which provides a structured representation for documents and defines how to access the document structure through scripts. DOM is composed of nodes. After the HTML is loaded, the rendering engine will generate a DOM tree in memory based on the HTML document. This article uses a small case to traverse the dom tree recursively. The core of the method is to determine whether the incoming data is an array, and then traverse the root node. Note that there must be an end condition when using recursion.