Article directory XMLHttpRequest object onreadystatechange event setRequestHeader handles the response to send a request to the server idea description request mode complete code

If you already know the basics of Ajax, you can start by thinking about it

The XMLHttpRequest object

All modern browsers support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).

To cope with all modern browsers:

  let xmlhttp;
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
  } else {// code for IE6, IE5
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

The onreadystatechange event

The onreadystatechange event is emitted whenever readyState changes.

The readyState property holds the state information for XMLHttpRequest.

attribute describe
onreadystatechange Stores the function (or function name) that is called whenever the readyState property changes.
readyState The XMLHttpRequest state exists. It goes from 0 to 4. 0: request not initialized 1: server connection established 2: request received 3: request processing 4: request completed and response ready
status 200: “OK”404: Page not found

When readyState is equal to 4 and the state is 200, the response is ready:

xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { var result = Xmlhttp. responseText try{resolve(JSON. Parse (result))}catch (e) {reject({errorMsg:' data format error '})}} else {// console.log('error:xmlhttp.status =', xmlhttp.status) reject(xmlhttp) } } }

setRequestHeader

XMLHttpRequest. SetRequestHeader () is to set the HTTP request header. This method must be called between the open() method and send(). If you assign a value to the same header multiple times, only one header that combines multiple values is generated.

If the Accept property is not set, the value that is sent () is the default value for this property /. Grammar:

xmlhttp.setRequestHeader(header, value);

Process the response

Several types of response properties for the XMLHttpRequest() object

attribute describe
responseText Gets the response data as a string.
responseXML Gets the response data in XML form.

Parse and manipulate the responseText property that contains the HTML document

There are three main ways to parse these HTML tags:

  1. useXMLHttpRequest.responseXMLattribute
  2. Pass content throughfragment.body.innerHTMLInjects into a document fragment and iterates over the fragment in the DOM
  3. If you know the contents of your HTML document in advance, use itRegExp

The third way is not recommended, because if the HTML code changes slightly, this method would be likely to fail, generally use the XMLHttpRequest directly. The responseXML property

Send a request to the server

To send a request to the server, we use the open() and send() methods of the XMLHttpRequest object

Open () : Specifies the type of request, the URL, and whether the request should be processed asynchronously.

open(method,url,async)

Parameter description:

  • Method: type of request;
  • GET or POST URL: The location of the file on the server
  • Async: true or false

Send () : Send the request to the server.

send(string)

Parameter description:

  • String: Used for POST requests only

My code:

 xmlhttp.open(arg.method || 'GET', arg.url, true);
 arg.headers = arg.headers || {};
  for (let key in arg.headers){
      xmlhttp.setRequestHeader(key, arg.headers[key]);
  }
  xmlhttp.send(arg.data);

Thinking that

HTTP requests can be made in several ways: GET, POST, PUT… , which starts with the public part and wraps a createXMLHttp () method

  1. Create the XMLHttpRequest object
  2. Handles the onreadystatechange event, specifying the task to be executed when the server response is ready to be processed
  3. Open () specifies the type of request, the URL, and whether the request is processed asynchronously
  4. SetRequestHeader () sets the request header
  5. Send () sends the request to the server

The createXMLHttp () method takes an object arg as an argument and returns a Promise object.

Arg. Method: The type of the request, arg. URL: The URL of the request, arg. Headers: The request header, which stores arg. Data as an object: Used only for POST requests
function createXMLHttp(arg) { return new Promise((resolve,reject) => { arg = arg || {} let xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 //xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { var result = Xmlhttp. responseText try{resolve(JSON. Parse (result))}catch (e) {reject({errorMsg:' data format error '})} else { console.log('error:xmlhttp.status =', xmlhttp.status) reject(xmlhttp) } } } if(Vue.prototype.$ajax.interceptors && Vue.prototype.$ajax.interceptors.request){ Vue.prototype.$ajax.interceptors.request(arg) } xmlhttp.open(arg.method || 'GET', arg.url, true); arg.headers = arg.headers || {}; for (let key in arg.headers){ xmlhttp.setRequestHeader(key, arg.headers[key]); } xmlhttp.send(arg.data); })}

Encapsulating the POST method

Stitching URLs, formatting data, and calling CreateXMLHttp to create POST data are all objects, which are easy to handle. Body = JSSON.stringify (body) will do the job

Vue.prototype.$ajax.post = function post(url,body) { url = Vue.prototype.$ajax.baseURL + url; body = JSON.stringify(body) let token = window.sessionStorage.getItem('token') token = (token ! = 'undefined') ? JSON.parse(token) : '' return createXMLHttp({ method:'POST', url, headers:{ 'Content-type':'application/json; charset=utf-8', 'token': token }, data:body }) }

Encapsulating the GET method

Get requests for native Ajax:

xmlhttp.open("GET","/try/ajax/demo_get.php? t=" + Math.random(),true); xmlhttp.send();
xmlhttp.open("GET","/try/ajax/demo_get2.php? fname=Henry&lname=Ford",true); xmlhttp.send();

My goal is to be able to send requests with objects as parameters in addition to the concatenation of characters above

this.$ajax.get('/v1/user', { pageSize:this.pageSize, pageNum:this.pageNum }) this.$ajax.get('/v1/menuInfo? id='+1).then(res =>{}) this.$ajax.get('/v1/menuInfo? id=1&lname=Ford').then(res =>{})

When the parameter is an object, to convert the key:value into a string key=value, and to connect multiple parameters with ampersand, it is necessary to first judge whether the last character of the URL is ‘? ‘If it’s not, I have to make it up front ‘? ‘

let paramsArray = [] for(let key in params){ paramsArray.push(key + '=' + params[key]) } if(paramsArray.length){ url = url.indexOf('? ') > 1? url : (url + '? ') if (url.indexOf('? ')! = url.length - 1){ url += '&' } url += paramsArray.join('&') }

Get method encapsulation:

Vue.prototype.$ajax.get = function get(url,params) { url = Vue.prototype.$ajax.baseURL + url; let paramsArray = [] for(let key in params){ paramsArray.push(key + '=' + params[key]) } if(paramsArray.length){ url = url.indexOf('? ') > 1? url : (url + '? ') if (url.indexOf('? ')! = url.length - 1){ url += '&' } url += paramsArray.join('&') } let token = window.sessionStorage.getItem('token') token = (token ! = 'undefined') ? JSON.parse(token) : '' return createXMLHttp({ method:'GET', url, headers:{ 'accept':'application/json', 'Content-type':'application/json; charset=utf-8', 'token': token } }) }

In order to facilitate the use of plug-in VUE plug-in

//./plugin/MyAjax.js var MyAjax = {}; MyAjax. Install = function (Vue) {Vue. Prototype. $ajax = {baseURL: 'XXXXXXXXXXXXXXXXXXXX / / domain name server: port}} module. Exports =  MyAjax;
//main.js
import myAjax from './plugin/MyAjax'
Vue.use(myAjax)

Request way

The request is done in a similar way to Axios

$ajax. POST ('/ V1 /login', {userName:this.account, '/ V1 /login', $ajax. passWord:this.password }).then(res =>{ // console.log(res) }) this.$ajax.post('/v1/group',this.groupInfo).then(res =>{ if (! Res. The error) {/ / this. $router. The back ()}}) / / GET request this. $ajax. GET ('/v1 / xx? userName='this.userName).then(res =>{ // console.log(res) }) this.$ajax.get('/v1/user', { pageSize:this.pageSize, pageNum:this.pageNum }).then(res =>{ console.log(res) }) this.$ajax.get('/v1/menuInfo? id='+1).then(res =>{}) this.$ajax.get('/v1/menuInfo? id=1&lname=Ford').then(res =>{})

The complete code

var MyAjax = {}; MyAjax.install = function (Vue) { Vue.prototype.$ajax = { baseURL:'xxxxxxxxxxxxxxxxxxxx' } function createXMLHttp(arg) {  return new Promise((resolve,reject) => { arg = arg || {} let xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 //xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { var result = Xmlhttp. responseText try{resolve(JSON. Parse (result))}catch (e) {reject({errorMsg:' data format error '})} // console.log( Vue.prototype.$ajax.result) } else { console.log('error:xmlhttp.status =', xmlhttp.status) reject(xmlhttp) } } } if(Vue.prototype.$ajax.interceptors && Vue.prototype.$ajax.interceptors.request){ Vue.prototype.$ajax.interceptors.request(arg) } xmlhttp.open(arg.method || 'GET', arg.url, true); arg.headers = arg.headers || {}; for (let key in arg.headers){ xmlhttp.setRequestHeader(key, arg.headers[key]); } xmlhttp.send(arg.data); }) } Vue.prototype.$ajax.get = function get(url,params) { url = Vue.prototype.$ajax.baseURL + url; let paramsArray = [] for(let key in params){ paramsArray.push(key + '=' + params[key]) } if(paramsArray.length){ url = url.indexOf('? ') > 1? url : (url + '? ') if (url.indexOf('? ')! = url.length - 1){ url += '&' } url += paramsArray.join('&') } let token = window.sessionStorage.getItem('token') token = (token ! = 'undefined') ? JSON.parse(token) : '' return createXMLHttp({ method:'GET', url, headers:{ 'accept':'application/json', 'Content-type':'application/json; charset=utf-8', 'token': token } }) } Vue.prototype.$ajax.post = function post(url,body) { url = Vue.prototype.$ajax.baseURL + url; body = JSON.stringify(body) let token = window.sessionStorage.getItem('token') token = (token ! = 'undefined') ? JSON.parse(token) : '' return createXMLHttp({ method:'POST', url, headers:{ 'Content-type':'application/json; charset=utf-8', 'token': token }, data:body }) } Vue.prototype.$ajax.put = function put(url,body) { url = Vue.prototype.$ajax.baseURL + url; body = JSON.stringify(body) let token = window.sessionStorage.getItem('token') token = token? JSON.parse(token) : '' return createXMLHttp({ method:'PUT', url, headers:{ 'Content-type':'application/json; charset=utf-8', 'token': token }, data:body }) } Vue.prototype.$ajax.DELETE = function DELETE(url,body) { url = Vue.prototype.$ajax.baseURL + url; body = JSON.stringify(body) let token = window.sessionStorage.getItem('token') token = token? JSON.parse(token) : '' return createXMLHttp({ method:'DELETE', url, headers:{ 'Content-type':'application/json; charset=utf-8', 'token': token }, data:body }) } } module.exports = MyAjax;