AJAX Brief Explanation

Understanding AJAX

  • AJAXfull nameasync javascript and xml
  • Is the ability to interact with the front and back
  • That is, the tool for our client to send messages to the server, and the tool for receiving responses
  • It is a function of the default asynchronous execution mechanism
  • Previously:
    • Enter something in the browser address bar to display a page
    • Enter a php address in the browser address bar, and the content returned by php is given to the browser
  • It is:
    • js to request a php address
    • The content of PHP output will not be displayed directly on the browser
    • Instead, the content returned by PHP is given to the language js
    • If you still want him to be displayed on the page, then you need js to render, such as:document.write()

AJAX asynchronous

Four steps to use AJAX

  1. Create an ajax object, synchronize the code
  2. Configuration request information, synchronization code
  3. Send request, asynchronous code
    • Determine whether it is a "synchronous request" or "asynchronous request" according to the third parameter of open
    • But it is asynchronous code
  4. Accept response, asynchronous code

Writing suggestions

  • Asynchronous request:
    • The order of writing codes is: 1–>2–>3–>4
    • The writing order can also be: 1–>2–>4–>3
  • Synchronization request:
    • The writing order must be: 1–>2–>4–>3
  • in conclusion:
    • No matter if you send a synchronous or asynchronous request
    • Our code writing order is: 1–>2–>4–>3
  • Suggest:
    • Don’t send synchronous ajax requests as a last resort

Use of AJAX

  • There is a built-in constructor in js to create AJAX objects
  • After creating the AJAX object, we use the method of the AJAX object to send requests and receive responses

1. Create an AJAX object

  • The ajax object can help us send ajax requests
// IE9及其以上
const xhr = new XMLHttpRequest()
// IE9以下
const xhr = new ActiveXObject('Mricosoft.XMLHTTP');

2. Configure link information

  • The open method in the AJAX object is to configure the request information
  • xhr.open('请求方式','请求地址','是否异步');
  • The first parameter: the request method of this request: get, post, put
  • The second parameter: is the URL address of this request
  • The third parameter: whether this request is asynchronous or not, the default true means asynchronous, false means synchronous
const xhr = new XMLHttpRequest();

// 以GET的请求方式,向date.php文件发送请求
xhr.open('get','./date.php');

4. Accept the response

  • Because js and php interact, the output content of php is given to js, ​​so an event is used to receive
const xhr = new XMLHttpRequest();
xhr.open('get','./date.php');

// 标准浏览器
xhr.onload = function(){
    
    
	// 这个函数会在AJAX请求完成的时候触发
	// 我们在这里就能得到后端返回的数据了
	console.log('请求已经完成');
	console.log(xhr);
	console.log(xhr.response);
	// 可以把响应的内容显示在指定的div中
	 document.getElementById('box').innerHTML = xhr.response;
}
// IE低版本
xhr.onreadystatechange = function(){
    
    
	if(xhr.readyState==4&&/^2\d{2}$/.test(xhr.status)){
    
    
    // 404就不会输出
    console.log('确定状态码是4');
    console.log(xhr.status);
    console.log(xhr.responseText);
	}
}

3. Send the request

  • Use the ajax object.send() method
  • Means to send out this request that I configured
const xhr = new XMLHttpRequest();
xhr.open('get','./deta.php');
xhr.onload = function(){
    
    
	console.log('请求已经完成');
	console.log(xhr);
	console.log(xhr.response);
}
//发送请求
xhr.send();

Receive response

AJAX status code

  • AJAX status code-xhr.readyState
  • It is used to represent a certain state in the entire process of an AJAX request
    • readyState === 0: Indicates that the initialization is not completed, that is, the openmethod has not been executed
    • readyState === 1l: Indicates that the configuration information has been completed, that is, the execution is completeopen
    • readyState === 2: Indicates that the sendmethod has been executed
    • readyState === 3: Indicates that the response content is being parsed
    • readyState === 4: Indicates that the response content has been parsed and can be used on the client
  • At this time, we will find that in the entire process of an AJAX request, only when readyState===4, we can use the data that the server gives us normally.
  • Therefore, with http status code 200-299
    • There is a member in an AJAX object calledxhr.status
    • This member records the http status code of this request
  • When both conditions are met, the request is completed normally

readyStateChange

  • There is an event in the AJAX object, called readyStateChangeevent
  • This event is specifically used to monitor readyStatethe behavior of the AJAX object's value change
  • That is, as long as readyStatethe value changes, then the event will be triggered
  • So we are monitoring AJAX in this event to see if it has readyStatereached 4
const xhr = new XMLHttpRequest();
xhr.open('get','./data.php');

xhr.send();
xhr.onreadyStateChange = function(){
    
    
	// 每次 readyState 改变的时候都会触发该事件
	// 我们就在这里判断 readyState 的值是不是到4
	// 并且 HTTP 的状态码是不是200-299
	if(xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)){
    
    
		// 这里表示验证通过
		// 我们就可以获取服务端给我们响应的内容了
		console.log(xhr.responseText);
	}
}

responseText

  • responseTextMembers in the AJAX object
  • It is used to record the content of the response body given to us by the server
  • So we can use this member to get the content of the response body
const xhr = new XMLHttpRequest();

xhr.open('get','./data.php');

xhr.send();

xhr.onreadyStateChange = function(){
    
    
	if(xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)){
    
    
		/我们在这里直接打印xhr.reaponseText 来查看服务端给我们返回的内容
		console.log(xhr.responseText);
	}
}

Carry parameters when using AJAX to send a request

  • We use AJAX to send requests can also carry parameters
  • Parameters are some information given to him when interacting with the background
  • But there is still a difference between the two methods of carrying parameters get and post

Send a get request with parameters

  • The parameters of the get request can be spliced ​​directly after the url.
const xhr = new XMLHttpRequest();
//直接在地址后面加一个?,然后以key=value的形式传递
//两个数据之间以&分割
xhr.open('get','./date.php?a=100$b==200');
xhr.send();
- 这样服务端就能接受到两个参数
- 一个是a,值是100
- 一个是b,值是200

Send a post request with parameters

  • The parameters of the post request are carried in the request body, so there is no need to splice after the url
  • application/x-www=form-urlencodedThe data format represented iskey=value&key=value
const xhr = new XMLHttpRequest();
xhr.open('get','./data.php');
//如果是用AJAX对象发送post请求,必须要先设置一下请求头中的content-type
//告诉下服务端我给你的是一个什么样子的数据格式
xhr.setRequesHeader('content-type','application/x-www-form-urlencoded');
//请求体直接在send的时候写在()里面就行
//不需要问号,直接就是'key=value&key=value'的形式
xhr.send('a=100&b=200');

Encapsulate AJAX

  • Ajax is too troublesome to use, because you have to write a lot of code every time
  • Then we encapsulate an ajax method to make it easier for us to use

Decide how to use it

  • Because there are some content that can not be passed, we can use the default value, so choose the way the object passes the parameters
// 使用的时候直接调用,传递一个对象就可以
ajax({
    
    
  url: '', // 请求的地址
  type: '', // 请求方式
  async: '', // 是否异步
  data: '', // 携带的参数
  dataType: '', // 要不要执行 json.parse
  success: function () {
    
    } // 成功以后执行的函数
})

Encapsulation

function ajax(options) {
    
    
  // 先准备一个默认值
  var defInfo = {
    
    
    url: '', // 地址不需要默认值
    type: 'GET', // 请求方式的默认值是 GET
    async: false, // 默认值是异步
    data: '', // 参数没有默认值
    dataType: 'string', // 默认不需要执行 json.parse
    success () {
    
    }, // 默认是一个函数
  }

  // 先来判断一下有没有传递 url,如果没有,直接抛出异常
  if (!options.url) {
    
    
    throw new Error('url 必须传递')
  }

  // 有了 url 以后就,我们就把用户传递的参数和我们的默认数据合并
  for (let key in options) {
    
    
    defInfo[key] = options[key]
  }

  // 接下来的一切我们都是使用我们的 defInfo 就可以了
  // 第一步就是判断参数 data
  // data 可以不传递,可以为空
  // data 也可以是一个 key=value&key=value 格式的字符串
  // data 也可以是一个对象
  // 否则就抛出异常
  if (!(typeof defInfo.data === 'string' && /^(\w+=\w+&?)*$/.test(defInfo.data) || Object.prototype.toString.call(defInfo.data) === '[object Object]')) {
    
    
    throw new Error('请按照要求传递参数')
  }

  // 参数处理完毕以后,在判断 async 的数据类型
  // 只能传递 布尔数据类型
  if (typeof defInfo.async !== 'boolean') {
    
    
    throw new Error('async 参数只接受布尔数据类型')
  }

  // 在接下来就判断 type
  // 请求方式我们只接受 GET 或着 POST
  if (!(defInfo.type.toUpperCase() === 'GET' || defInfo.type.toUpperCase() === 'POST')) {
    
    
    throw new Error('目前本插件只接受 GET 和 POST 方式,请期待更新')
  }

  // 接下来就是判断 success 的判断,必须是一个函数
  if (Object.prototype.toString.call(defInfo.success) !== '[object Function]') {
    
    
    throw new Error('success 只接受函数数据类型')
  }

  // 参数都没有问题了
  // 我们就要把 data 处理一下了
  // 因为 data 有可能是对象,当 data 是一个对象的时候,我们要把它转换成一个字符串
  var str = ''
  if (Object.prototype.toString.call(defInfo.data) === '[object Object]') {
    
    
    for (let attr in defInfo.data) {
    
    
      str += `${
      
      attr}=${
      
      defInfo.data[attr]}&`
    }
    str = str.slice(0, -1)
    defInfo.data = str
  }

  // 参数全部验证过了以后,我们就可以开始进行正常的 ajax 请求了
  // 1. 准备一个 ajax 对象
  //    因为要处理兼容问题,所以我们准备一个函数
  function createXHR() {
    
    
    if (XMLHttpRequest) {
    
    
      return new XMLHttpRequest()
    } else {
    
    
      return new ActiveXObject('Microsoft.XMLHTTP')
    }
  }

  // 2. 创建一个 ajax 对象
  var xhr = createXHR()

  // 3. 进行 open
  xhr.open(defInfo.type, defInfo.url + (defInfo.type.toUpperCase() === 'GET' ? `?${
      
      defInfo.data}&_=${
      
      new Date().getTime()}` : ''), defInfo.async)

  if (defInfo.type.toUpperCase() === 'POST') {
    
    
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  }

  // 4. 进行 send
  xhr.send((defInfo.type.toUpperCase() === 'POST' ? `${
      
      defInfo.data}` : ''))

  // 5. 接受响应
  xhr.onreadystatechange = function () {
    
    
    if (xhr.readyState === 4 && /2\d{2}/.test(xhr.status)) {
    
    
      // 表示成功,我们就要执行 success
      // 但是要进行 dataType 的判断
      if (defInfo.dataType === 'json') {
    
    
        defInfo.success(JSON.parse(xhr.responseText))
      } else {
    
    
        defInfo.success()
      }
    }
  }
}

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/113998282