Native js implements Ajax requests, including get and post

Keywords: Javascript JQuery JSON IE

Now the web requests data from the server, many of which use Ajax, but they are all wrapped with JQuery. In the previous project, because JQuery cannot be referenced, it can only be used in the native, not to speak much, please see the code.

 1 /*-------------------Ajax start--------------------*/
 2 
 3 function ajax(options) {
 4     options = options || {};
 5     options.type = (options.type || "GET").toUpperCase();
 6     options.dataType = options.dataType || "json";
 7     var params = formatParams(options.data);
 8     var xhr;
 9  
10     //Establish - First step
11     if (window.XMLHttpRequest) {
12       xhr = new XMLHttpRequest();
13     } else if(window.ActiveObject) {         //IE6 And below
14       xhr = new ActiveXObject('Microsoft.XMLHTTP');
15     }
16  
17     //Connect and send - The second step
18     if (options.type == "GET") {
19       xhr.open("GET", options.url + "?" + params, true);
20       xhr.send(null);
21     } else if (options.type == "POST") {
22       xhr.open("POST", options.url, true);
23       //Set the content type when the form is submitted
24       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
25       xhr.send(params);
26     }
27 
28      //Receive - The third step
29     xhr.onreadystatechange = function () {
30       if (xhr.readyState == 4) {
31         var status = xhr.status;
32         if (status >= 200 && status < 300 || status == 304) {
33           options.success && options.success(xhr.responseText, xhr.responseXML);
34         } else {
35           options.error && options.error(status);
36         }
37       }
38     }
39   }
40 
41 //Format parameters
42 function formatParams(data){
43     var arr = [];
44     for (var name in data) {
45       arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
46     }
47     arr.push(("v=" + Math.random()).replace(".",""));
48     return arr.join("&");
49 }
50 
51 /*-------------------Ajax end-------------------*/

There are three steps to encapsulate Ajax:

Step 1: create the required objects. XMLHttpRequest is mainly used here. Pay attention to the need to consider the early IE;

The second step: connect and send;

The third step: receiving;

In order to format the request parameters, a formatparames (data) function is encapsulated here.

Posted by bernouli on Tue, 31 Mar 2020 01:09:43 -0700