Ajax related knowledge points in jQuery

Students who learn JavaScript know that AJAX (async javascript and
xml) translation is called asynchronous JavaScript and XML. It is also a troublesome thing to send network requests in native js, and it is those steps every time.

Let's first review how to send an ajax network request in native js

Classic 4 steps

1. Native js ajax network request

    // IE9及以上
    // const xhr = new XMLHttpRequest()
    // IE9以下
    // const xhr = new ActiveXObject('Mricosoft.XMLHTTP')

    // 对于这个兼容写法我们可以用一个函数来封装
    function createXHR() {
    
    
      var req = null;
      if (window.XMLHttpRequest) {
    
    
        // 如果有这个XMLHttpRequest对象就直接使用
        req = new XMLHttpRequest();
      } else {
    
    
        // 否则就使用IE8一下的写法
        req = new ActiveXObject("Microsoft.XMLHTTP");
      }
      return req;
    }
    // 第一步:创建ajax对象
    var xhr = createXHR(); //这样就拿到了一个ajax对象
    // 第二步:配置网络请求信息

    xhr.open('get', './demo.php', true)
    //  xhr.open('get/post','要发送网络请求去哪个地址',同步还是异步默认 true 表示异步,false 表示同步)
    //  如果是get请求有参数需要拼接在地址后面,例如'./demo.php?id=2&name=sanqi'
    // 如果是post请求,参数就要放在send()里面,例如:xhr.send('id=2&name=sanqi')
    // 第三步:发送网络请求
    xhr.send() //
    // 第四部:判断响应状态拿到数据
    xhr.onreadyStateChange = function () {
    
    
      // 每次 readyState 改变的时候都会触发该事件
      // 我们就在这里判断 readyState 的值是不是到 4
      // 并且 http 的状态码是不是 200 ~ 299
      if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
    
    
        // 这里表示验证通过
        // 我们就可以获取服务端给我们响应的内容了
        console.log(xhr.response);
      }
    }


Here are the 5 states of readyState

  • readyState --> 0: indicates that the initialization is not completed, that is, the open method has not been executed
  • readyState --> 1: Indicates that the configuration information has been completed, that is, after executing open
  • readyState --> 2: Indicates that the send method 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 side

The above is the native js sending an ajax network request

2. About ajax network request using jQuery

When we are learning jquery, we understand that everyone is saying that all jq is encapsulated for us, and these network requests do not need to be written by us. Even so, we still can't blindly use it. We still need to understand it before using it. .

(1). Use jquery to send get request

The following unified back-end code uses the file name: test.php this file

<?php
header('content-type:text/html;charset=utf-8;');
  $id = $_REQUEST['id'];
  $name = $_REQUEST['name'];
  $arr = [
    'id' => $id,
    'name' => $name
  ];
  echo json_encode($arr);
?>

Use jquery to send get request

      $.get('./test.php','id=999&name=三七安',function (res) {
    
     
      //第一个参数是请求的地址
      //第二个参数是要发送给服务器的数据
      //第三个参数是成功时的回调函数,里面包含服务返回给我们的数据
      //第四个参数是我们希望拿到的数据格式:有几种选择:json,text,html,xml,script
        console.log(res);
       },'json')

You can see that the request was sent successfully
Insert picture description here
(2) Use jquery to send a post request

	 $.post('./test.php',{
    
    id:123,name:'post请求'},function (res) {
    
     
	 //这里其他参数和get请求一致的
	 //注意,这里的传输数据我用 对象的格式来写,也能发送请求成功,也就是说
	 //无论是get请求还是post请求,想服务端传数据,既可以使用字符串格式也可以使用对象格式
        console.log(res);
       },'json')

This is the page where the request was successful
Insert picture description here

(3) Use jquery to send a comprehensive ajax request

Let's take a look at the grammar first

    // 使用 $.ajax 方法
    // 只接受一个参数,是一个对象,这个对象对当前的请求进行所有的配置
    $.ajax({
    
    
      url: './ajax', // 必填,请求的地址
      type: 'GET', // 选填,请求方式,默认是 GET(忽略大小写)
      data: {
    
    }, // 选填,发送请求是携带的参数
      dataType: 'json', // 选填,期望返回值的数据类型,默认是 string
      async: true, // 选填,是否异步,默认是 true
      success() {
    
    }, // 选填,成功的回调函数
      error() {
    
    }, // 选填,失败的回调函数
      cache: true, // 选填,是否缓存,默认是 true
      context: div, // 选填,回调函数中的 this 指向,默认是 ajax 对象
      status: {
    
    }, // 选填,根据对应的状态码进行函数执行
      timeout: 1000, // 选填,超时事件
    })

It seems that you have to fill in many parameters every time, but in fact, most of the parameters are optional. We only need to fill
in the actual situation. In the compiler, directly input ajax can also quickly generate part of the code.
Insert picture description here
Send the ajax request code

$.ajax({
    
    
       type: "get",
       url: "./test.php",
       data: {
    
    
         id:000,
         name:'发送$.ajax请求的演示'
       },
       dataType: "json",
       success: function (response) {
    
    
         console.log(response);
       }
     });

Open the web page and you can see that the data we retrieved from the backend
Insert picture description here
are supplemented with several Ajax global functions, also called hook functions, which are functions executed at a certain stage in the entire Ajax request process, and it is any Ajax request Will trigger.

1. ajaxStart , this function will be triggered when any request starts

$(window).ajaxStart(function () {
    
    
    console.log('有一个请求开始了')
})

2. ajaxSend , this request will be triggered before any request is ready to send .

$(window).ajaxSend(function () {
    
    
    console.log('有一个要发送出去了')
})

3.ajaxSuccess , this function will be triggered when any request is successful.

$(window).ajaxSuccess(function () {
    
    
    console.log('有一个请求成功了')
})

4.ajaxError , this function will be triggered when any request fails.

$(window).ajaxError(function () {
    
    
    console.log('有一个请求失败了')
})

5.ajaxComplete , this function will be triggered when any request is completed

$(window).ajaxComplete(function () {
    
    
    console.log('有一个请求完成了')
})

6.ajaxStop, this function will be triggered when any request ends

$(window).ajaxStop(function () {
    
    
    console.log('有一个请求结束了')
})

Well, the above is the knowledge related to jQuery's ajax network request. I hope to make a little progress for everyone. Some knowledge is also from the Internet. If there are errors or omissions, please point out that Xiaobai must correct them in time, thank you!!!

Humility makes one progress, pride makes one lag behind.

Guess you like

Origin blog.csdn.net/weixin_43314255/article/details/114444344