This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact

preface

Now that we’ve learned about AJAX, we’ve wrapped GET requests. Should POST requests be improved as well?

This section looks at AJAX POST requests

A POST request

Similar to GET, whenever we want to send an AJAX request, we need to do 5 steps:

The five department of AJAX

  1. Create an asynchronous object XMLHTTP;
new XMLHttpRequest(); 
new ActiveXObject("Microsoft.XMLHTTP"); 
Copy the code
  1. Set the request mode and request address;
xmlhttp.open("POST"."01-ajax-get.php".true);
Copy the code
  1. Send a request;
xmlhttp.send();
Copy the code
  1. Monitor state changes;

The onReadyStatechange event listens for the sent statechange, and the request ends when the readyState is 4.

  1. Process the returned results;

Status is used to determine whether the request was successful and process the returned result

In particular: if you need to POST data as an HTML form would, use setRequestHeader() to add HTTP headers. Then specify the data you want to send in the send() method:

xmlhttp.open("POST"."ajax_test.html".true); 
xmlhttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); 
xmlhttp.send("fname=Henry&lname=Ford");
Copy the code

So make the Ajax code you wrapped earlier a little better: add a request type parameter, type

function ajax(type,url,obj,timeout,success,error){
    // 0. Convert the object to a string
    var str = objToString(obj); 

    // 1. Create an asynchronous object XMLHTTP;
    var xmlhttp,timer; 
    if (window.XMLHttpRequest){
      xmlhttp=new XMLHttpRequest(); 
    } else{// code for IE6, IE5 
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    }

    // 2. Set the request mode and address.
    // Determine whether the request type is POST or GET
    if (type === 'GET') {
            xmlhttp.open(type,url+"? t=" +str,true);
    // 3.
        xmlhttp.send();
    }else{
                    xmlhttp.open(type,url,true);
                    SetRequestHeader (header,value); setRequestHeader(header,value);
                    xmlhttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded"); 
            // 3.
                    xmlhttp.send(str);

    }   

    // 4.
    xmlhttp.onreadystatechange = function(){
            clearInterval(timer);
        if (xmlhttp.readyState === 4) {
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status == 304) {
                // 5. Process the returned result;
                success(xmlhttp);// Callback after success;
            }else{
                error(xmlhttp);// Callback after failure;}}}}/ / processing obj
    function objToString(obj){
      obj.t = new Date().getTime();
      var res =[];
      for(var key in obj){
            // We need to convert the key and value to a non-Chinese form, because the URL cannot have Chinese. Use encodeURIComponent ();
        res.push(encodeURIConponent(key) + "=" +encodeURIConponent(obj.[key]));
      }
      return res.join("&");
    }

    // Determine whether the timeout is passed in
    if(timeout){
            timer = setInterval(function(){
                    xmlhttp.abort();// Interrupt the request
                    clearInterval(timer); },timeout); }}Copy the code

So we wrap the POST request

END

That’s all for this article

If you have any questions, please leave a comment