Summary of relevant knowledge points of ajax in jQuery

Summary of relevant knowledge points of ajax in jQuery

Preface

Students who learn JavaScript know that AJAX (async javascript and
xml) Translation is called asynchronous JavaScript and XML. It is also a hassle to use it in native js to send network requests, and each time there are those few steps.

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

Classic 4 Steps

1. Native js ajax network request

 // IE9 and above // ​​const xhr = new XMLHttpRequest()
 // IE9 and below // const xhr = new ActiveXObject('Mricosoft.XMLHTTP')

 // For this compatible writing method, we can use a function to encapsulate function createXHR() {
 var req = null;
 if (window.XMLHttpRequest) {
 // If you have this XMLHttpRequest object, just use req = new XMLHttpRequest();
 } else {
 // Otherwise, use the IE8 or later method req = new ActiveXObject("Microsoft.XMLHTTP");
 }
 return req;
 }
 // Step 1: Create an ajax object var xhr = createXHR(); // This way you get an ajax object // Step 2: Configure network request information xhr.open('get', './demo.php', true)
 // xhr.open('get/post', 'To which address do you want to send the network request', synchronous or asynchronous, the default is true for asynchronous and false for synchronous)
 // If the get request has parameters, they need to be concatenated after the address, for example './demo.php?id=2&name=sanqi'
 // If it is a post request, the parameters should be placed in send(), for example: xhr.send('id=2&name=sanqi')
 // Step 3: Send network request xhr.send() //
 // Part 4: Determine the response status and get the data xhr.onreadyStateChange = function () {
 // This event is triggered every time the readyState changes // We will check here whether the value of readyState is 4
 // And the http status code is 200 ~ 299
 if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
 // This means the verification is passed // We can get the content of the response from the server console.log(xhr.response);
 }
 }


Here are the 5 states of readyState

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

The above is the native js sending an ajax network request

2. About ajax network requests using jQuery

When we were learning jQuery, we realized that everyone was saying that jQuery has encapsulated everything for us, and we don't need to write these network requests. Even so, we still can't be blind, and we still need to understand it in detail before using it.

(1). Use jQuery to send a get request

The following unified backend code uses the file name: test.php

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

Sending a get request using jQuery

  $.get('./test.php','id=999&name=三七安',function (res) { 
  //The first parameter is the requested address //The second parameter is the data to be sent to the server //The third parameter is the callback function when successful, which contains the data returned by the service //The fourth parameter is the data format we want to get: there are several options: json, text, html, xml, script
  console.log(res);
  },'json')

You can see that the request was sent successfully.

(2) Send a post request using jQuery

	 $.post('./test.php',{id:123,name:'post request'},function (res) { 
	 //The other parameters here are the same as those of the get request //Note that I write the transmission data here in object format, and the request can be sent successfully, that is to say //Whether it is a get request or a post request, if you want to send data to the server, you can use either string format or object format console.log(res);
  },'json')

This is the page where the request was successful

(3) Use jQuery to send a comprehensive ajax request

Let’s first look at the syntax

 // Use the $.ajax method // It only accepts one parameter, which is an object. This object performs all configurations for the current request. $.ajax({
  url: './ajax', // Required, requested address type: 'GET', // Optional, request method, default is GET (ignore case)
  data: {}, // Optional, the parameter to be carried when sending the request dataType: 'json', // Optional, the data type of the expected return value, the default is string
  async: true, // Optional, whether to enable asynchronous operation, default is true
  success() {}, // Optional, callback function for success error() {}, // Optional, callback function for failure cache: true, // Optional, whether to cache, default is true
  context: div, // Optional, this in the callback function points to, the default is the ajax object status: {}, // Optional, execute the function according to the corresponding status code timeout: 1000, // Optional, timeout event })

It seems that we have to fill in a lot of parameters every time, but in fact most of the parameters are optional. We just need to fill them in according to the actual situation.

In the compiler, you can also quickly generate some code by directly entering ajax

Send ajax request code

$.ajax({
  type: "get",
  url: "./test.php",
  data: {
   id:000,
   name:'Demo of sending $.ajax request'
  },
  dataType: "json",
  success: function (response) {
   console.log(response);
  }
  });

Open the webpage and you can see the data we got back from the backend

Here are some Ajax global functions, also called hook functions, which are functions executed at a certain stage in the entire Ajax request process and are triggered by any Ajax request.

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

$(window).ajaxStart(function () {
 console.log('A request has started')
})

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

$(window).ajaxSend(function () {
 console.log('One is about to be sent')
})

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

$(window).ajaxSuccess(function () {
 console.log('A request was successful')
})

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

$(window).ajaxError(function () {
 console.log('A request failed')
})

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

$(window).ajaxComplete(function () {
 console.log('A request has been completed')
})

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

$(window).ajaxStop(function () {
 console.log('A request has ended')
})

Summarize

This is the end of this article about the summary of relevant knowledge points of ajax in jQuery. For more relevant jQuery ajax knowledge points, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A simple example of implementing partial refresh using JQuery's Ajax request
  • jQuery's Ajax asynchronous request receives and returns JSON data examples
  • Cross-domain request: jQuery's ajax jsonp usage
  • jQuery Ajax request method and prompting the user to wait while processing
  • How to add a timeout to jQuery's Ajax request
  • jQuery.ajax cross-domain request webapi set headers solution
  • Jquery ajax request to export Excel table implementation code
  • Analysis and solution of the failure of Jquery Ajax request file download operation
  • A brief analysis of jQuery Ajax request parameters and returned data processing
  • Teach you how to terminate JQUERY's $.AJAX request

<<:  MySQL 5.7.18 free installation version configuration tutorial

>>:  Installation and deployment tutorial of the latest MySQL version 5.7.17 (64bit ZIP green version) under Win 8 or above

Recommend

Comprehensive understanding of line-height and vertical-align

Previous words Line-height, font-size, and vertica...

Analysis of MySQL's planned tasks and event scheduling examples

This article uses examples to describe MySQL'...

Summary of MySQL InnoDB architecture

Table of contents introduction 1. Overall archite...

CSS navigation bar menu with small triangle implementation code

Many web pages have small triangles in their navi...

How to install and use Server-U 14 version

Introducing Server-U software Server-U is a very ...

How does MySQL connect to the corresponding client process?

question For a given MySQL connection, how can we...

Detailed explanation of DOM style setting in four react components

1. Inline styles To add inline styles to the virt...

Analysis and description of network configuration files under Ubuntu system

I encountered a strange network problem today. I ...

Detailed explanation of the failure of MySQL to use UNION to connect two queries

Overview UNION The connection data set keyword ca...

Implementation of MySQL GRANT user authorization

Authorization is to grant certain permissions to ...