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.

Using ref to bind elements in Vue

 Vue provides us with a property to manipulate dom, ref. When bound to the dom element, it is used similar to the id. It is called through this.$refs, and it can also be bound to the component. It is very troublesome to obtain DOM elements in the previous native way. It needs to be obtained with such a long AP as: documentgetElementXXX/querySXXX.... Then jQuery was born to solve this pain point. The use of $("id") makes Our operation has become easier. But there are other problems, jQuery is just a library (plug-in) and cannot be used to build a framework. Now Vue can help us solve this problem. Vue also has its own method to obtain DOM, which is ref. It can get not only DOM elements but also components. If you add ref to the dom element, you can get the dom element, and if you add it to the component, you can get the component instance, and you can use the component method.

Use of custom events in Vue components.

 The parent component uses props to pass data (such as a method) to the child component, and the child component needs to use custom events to pass data back to the parent component! We can use v-on to bind custom events, and then pass them to subcomponents, which will call after receiving the method. Each Vue instance implements the Events interface, that is: use $on(eventName) to listen for events and $emit(eventName) to trigger events.