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 width property 100% and auto in css?

 width:auto: The default width value of block-level elements. When set to this value, the browser will automatically select an appropriate width value to adapt to the width of the parent element. When the width is set to 100%, the width of the child element box The value is equal to the parent's content, and as the parent's content automatically changes, after adding the padding and margin of the child element, its width remains unchanged, which is the difference from setting it to auto. But we most often use width:auto, because it is more flexible, width:100% is used less, because when adding padding or margin, this method is easy to make it exceed the parent box and destroy the original layout.

Access to XMLHttpRequest at 'http://localhost:8080/xxx' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 Due to browser same-origin policy restrictions. The Same Origin Policy is a convention. This is the main and essential security feature of the browser. Without the same-origin policy, normal browser functionality may be affected. The web is built on the same-origin policy, and browsers are just one implementation of the same-origin policy. The Same Origin Policy prevents JavaScript scripts from one domain from interacting with content from another domain. The so-called same origin (that is, the same domain) means that two pages have the same protocol, host and port.