Front and Back End Interaction Basics AJAX (I)

ajax

Ajax is: Ajax is “Asynchronous Javascript And XML”. Is a way of interacting with data at the front and back ends.

Ajax Basics

Block the jump when committing and intercept the information and submit it to the back end.

The object it depends on is XMLHttprequest

  • Create a new XMLHttpRequest object;

    let xhr = new XMLHttpRequest();
    Copy the code
  • Configure request Parameters

    xhr.open("get"."/checkUser".true); // True is asynchronous, false is synchronous
    Copy the code
  • Receive the returned value from the server

    Back and forth data ajax interaction, the server sends the information to the client is JSON and we need to perform a JSON.parse to object

     xhr.onload = function(){
        let res = JSON.parse(xhr.responseText);
     }
    Copy the code
  • Sending server

    xhr.send();
    Copy the code
User login example (get method)

Module dependency, koA koa-static-cache koa-router

Back-end server

router.get("/checkUserName".(ctx,next) = >{
    console.log(ctx.query.username);
    let res =  usersData.find(v= >v.username==ctx.query.username);
    if(res){
        ctx.body = {
            status:1.info:"User name is correct"
        };
    }else{
        ctx.body = {
            status:2.info:"User name error"}; }})Copy the code

The front-end processing

// Lose focus
document.querySelector(".inputStyle").onblur = function () {
  // console.log(this.value);
  let xhr = new XMLHttpRequest();
  xhr.open("get".`/checkUserName? username=The ${this.value}`.true);
  xhr.onload = function () {
    console.log(xhr.responseText);
    let obj = JSON.parse(xhr.responseText);
    document.querySelector(".exchange").innerHTML = obj.info;
    if (obj.status == 1) {
      document.querySelector(".exchange").style.color = "green";
    } else {
      document.querySelector(".exchange").style.color = "red";
    }
  }
  xhr.send();
}
Copy the code

Ajax GET requests

A url with the cords

  • Dynamic routing, parameter is required

    /getusername/:id

    Url: /getusername/ parameters (1,2,3,4….)

  • QueryString (get and Post can be used)

    /getusername

    url: /getusername? The username = xxxxx&username = XXXXX. Return an object with username=xxxxx&username= XXXXX on the backend

Ajax POST requests

Post is a text transfer parameter over HTTP. On the back end, you need to encode the POST data

You need to set the HTTP header format when sending data.

xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded");  // Default encoding
xhr.setRequestHeader("Content-type"."multipart/form-data");  // Binary encoding
xhr.setRequestHeader("Content-type"."application/json");  / / json encodingSetting it to JSON requires some encodinglet obj = JSON.parse({name:xxxx});
Copy the code
The node server

The receiver needs to use a KOA-body library, and the KOA-body is used as middleware to correctly read the message sent by post

router.post("/post".(ctx,next) = >{
    console.log(ctx.request.body);
    ctx.body = {
        status:1.info:"Post request successful"}})Copy the code
Front-end Page Configuration
document.querySelector("button").onclick = function () {
    let xhr = new XMLHttpRequest();
    xhr.open("post"."/post".true);
    xhr.onload = function () {
        console.log(xhr.responseText);
        // Get the return header
     // console.log(xhr.getAllResponseHeaders());
    // console.log(xhr.getResponseHeader("content-type"));
    }
    // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    // xhr.setRequestHeader("Content-Type","multipart/form-data"); // Binary encoding
    xhr.setRequestHeader("content-type"."application/json");
    // let data = "username= age=20";
    let data = JSON.stringify({
        username:"Fifty".age:20
    })
    xhr.send(data);
}
Copy the code
The method by which the front end gets the request header
  • getAllResponseHeaders

    • Get all header information
  • getResponseHeader(‘name’)

    • Gets the header for the specified name

    • console.log(xhr.getResponseHeader("content-type"));

Ajax synchronization and asynchrony

Asynchrony is in the process of synchronizing tasks, and Ajax requests have no effect. But if Ajax sets synchronization, the Ajax request can’t be executed until the synchronization task is complete. Our official recommendation is also to use asynchrony.

xhr.open("get"."/checkUser".true); // True is asynchronous, false is synchronous
Copy the code

onreadystatechange

In addition to onLoad, there is a function onreadyStatechange that checks the corresponding state of the server

Onreadystatechange: Holds a function that handles the server response and is executed whenever readyState changes.

ReadyState: Holds the status information of the server response.

  • 0: The request is not initialized (the proxy is created, but the open() method has not been called)
  • 1: The server connection is established.openMethod already called)
  • 2: The request has been receivedsendMethod has been called, and the header and state are available.
  • 3: Request processing (downloading,responseTextProperty already contains some data.
  • 4: Request completed and response ready (download completed)

Status Common status code

The HTTP status code describe
100 To continue. Continue to respond to the rest of the submission request
200 successful
301 Permanently move. Requests that the resource be permanently moved to a new location
302 Temporary move. Move to new location when requesting resource zero
304 Unmodified. The requested resource has not been modified compared to the last time, and the response does not contain the resource content
401 Not authorized and requires authentication
403 Is prohibited. Request denied
404 The server did not find the required resource
500 Server internal error. The server encountered an error and could not complete the request
503 The server is unavailable. The temporary service is overloaded and cannot process the request
    document.querySelector("button").onclick = function () {
        let xhr = new XMLHttpRequest();
        xhr.open("get"."/get/4".true);
        xhr.onload = function () {
            console.log(xhr.responseText);
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
        // xhr.onreadystatechange = function () {
        // if (xhr.readyState == 4) {
        // if (xhr.status == 200) {
        // console.log(xhr.responseText);
        / /}
        / /}
        // }
        xhr.send();
    }
Copy the code

XML data return

Data transfer in addition to JSON and XML, how to return XML.

page

document.querySelector("button").onclick = function(){
    let xhr = new XMLHttpRequest();
    xhr.open("get"."/xml".true);
    // If XML is not set on the back end, the front end can overwrite the content-type;
    xhr.overrideMimeType("text/xml");
    xhr.onload = function(){
        // console.log(xhr.responseText);
        // console.log(xhr.responseXML);
        // console.log(xhr.response)
        let name =  xhr.responseXML.getElementsByTagName("name") [1].innerHTML;
        console.log(name);
    }
    xhr.send();
}
Copy the code

The server

router.get("/xml".(ctx,next) = >{
    // ctx.set("content-type","text/xml");
    ctx.body = ` 
       
       
       
        nodejs
        
       
        6元
        
       
       
       
        react
        
       
        5元
        
         `
})
Copy the code

FormData file

Now when we transfer data, it’s just plain text data, so when we want to save files, videos, pictures and so on, we need to use formData.

Special file tag

The type file tag is required for file storage

<body>
    <input type="file" class="myfile" />
    <button>Click me upload file</button>
</body>
Copy the code
Post submission

Save files by POST.

Simple file storage
  • The front end

        document.querySelector("button").onclick = function(){
            let file = document.querySelector(".myfile").files[0];
            // console.log(files);
            let form = new FormData();
            form.append("img",file);
            // form.append("name"," name"); // form.append("name"," name");
            let xhr = new XMLHttpRequest();
            xhr.open("post"."/upload".true);
            xhr.onload = function(){
                console.log(xhr.responseText);
            }
            xhr.send(form);
        }
    Copy the code
  • Background server processing

    Note here that the saved file node helped me create a temporary path, which we will use the FS module to turn into the actual disk path

    router.post("/upload".(ctx,next) = >{
        console.log(ctx.request.body);
        console.log(ctx.request.files.img);
         let fileData =  fs.readFileSync(ctx.request.files.img.path);
        fs.writeFileSync("static/imgs/"+ctx.request.files.img.name,fileData);
        ctx.body = "Request successful";
    })
    Copy the code
Monitor the loading speed and loading progress

After the formData object is created. The onload event has several event hooks

Upload an event hook inside an event

  • Onloadstart Upload starts

  • Onprogress Data transfer in progress

    This method is used to calculate save speed and save progress using the following two objects.

    Progress of the calculation
    • Evt. total: total size to be transferred;
    • Evt.loaded: The size of the file currently uploaded;
    • ToFixed (0) as evt.loaded/evt.total*100
    Speed calculation
    • GetTime (); getTime(); getTime()
    • Evt.loaded = evt.loaded = evt.loaded = evt.loaded = evt.loaded = evt.loaded = evt.loaded
    • And finally, the file size divided by time equals speed
  • Onabort The upload operation is terminated

  • Onerror upload failed

  • Onload successfully uploaded

  • Onloadend Uploads complete (executes with or without success)

<body>
    <input type="file" class="myfile" />Progress: <progress value="0" max="100"></progress> <span class="percent">0%</Span > speed: <spanclass="speed">20b/s</span>
    <button>Click on the upload</button>
    <button>Cancel the upload</button>
</body>
<script>
    let xhr = new XMLHttpRequest();
    let btns = document.querySelectorAll("button");
    let stime;
    let sloaded;
    btns[0].onclick = function () {
        let file = document.querySelector(".myfile").files[0];
        let form = new FormData();
        form.append("myfile", file);
        xhr.open("post"."/fileUpload".true);
        xhr.onload = function () {
            console.log(xhr.responseText);
        }
        xhr.upload.onloadstart = function(){
            console.log("Start uploading");
            stime = new Date().getTime();
            sloaded = 0;
        }
        xhr.upload.onprogress = function(evt){
            let endTime = new Date().getTime();
            // Time difference;
            let dTime = (endTime - stime)/1000;
            // The size of the file uploaded in the current time
            let dloaded =  evt.loaded - sloaded;
            let speed = dloaded/dTime;
            let unit = "b/s";
            stime = new Date().getTime();
            sloaded = evt.loaded;
            if(speed/1024>1){
                unit = "kb/s";
                speed = speed/1024;
            }
            if(speed/1024>1){
                unit = "mb/s";
                speed = speed/1024;
            }
            document.querySelector(".speed").innerHTML = speed.toFixed(2)+unit;
            // console.log(speed.toFixed(2));
            // console.log(" uploading ");
            // The current file upload size evt.loaded
            // The size of the file to be uploaded
           let percent =  (evt.loaded/evt.total*100).toFixed(0);
        // console.log(percent);
            document.querySelector("progress").value = percent;
            document.querySelector(".percent").innerHTML = percent+"%";
        }
        xhr.upload.onload = function(){
            console.log("Upload successful");
        }
        xhr.upload.onloadend = function(){
            console.log("Upload completed");
        }
        xhr.upload.onabort = function(){
            console.log("Cancel upload");
        }
        xhr.send(form);
    }
    btns[1].onclick = function(){
        xhr.abort();
    }
Copy the code

The server

router.post("/fileUpload".(ctx,next) = >{
    console.log(ctx.request.files);
    let fileData =  fs.readFileSync(ctx.request.files.myfile.path);
    fs.writeFileSync("static/imgs/"+ctx.request.files.myfile.name,fileData);
    ctx.body = "Request successful";
})
Copy the code