Web front-end interview summary --Ajax

Ajax

1. Step Ajax sends the request to implement by native js?

  • By onload event registration:
// Create a xhr objects
var xhr = new XMLHttpRequest();
// 2. manner and path setting request
xhr.open('GET', '/time');
// 3. Send request
xhr.send(null);
// 4. Registration Event
xhr.onload = function () {
    // Get the response by the body in response to the responseText xhr
   console.log(this.responseText)
}

  Note: If the sending request of the post embodiment, the request needs to be set in the open and intermediate header send, send adding the parameter to be delivered (with format requirements: = connection attributes and values; connected & different properties).

var xhr = new XMLHttpRequest()
xhr.open('POST', '/query-post')
// set the Content-Type is application / x-www-form-urlencoded, which do not have to memorize lines of code, copy it to
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// need to submit the data to the server may send the parameter passing method
// format: name = zhangsan & age = 18
xhr.send('name=zhangsan&age=18')
xhr.onload = function () {
    console.log(this.responseText)
}
  • onload new HTML5 is the future of easy access in response to the event, use the browser to return to the past to obtain the contents of the time is onreadystatechange.
var xhr = new XMLHttpRequest()
Effect // open the first parameter setting method is a method request
xhr.open('POST', '/query-post')
// set the Content-Type is application / x-www-form-urlencoded, which do not have to memorize lines of code, copy it to
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// need to submit the data to the server may send the parameter passing method
// format: name = zhangsan & age = 18
xhr.send('name=zhangsan&age=18')
// Change the event onreadystatechange
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
    // subsequent logic ......
  }
} 

 Difference 2.ajax and axios, fetch the

Guess you like

Origin www.cnblogs.com/belongs-to-qinghua/p/11033138.html