AJAX notes

tags: ajax

AJAX

What exactly is Ajax?

  • ajax full name async javascript and XML (asynchronous JavaScript and XML)

  • It is the ability of front-end and back-end interaction, that is, the tool for our client to send messages to the server and the tool for receiving responses

  • AJAX is not a new programming language, but a new way to use existing standards.

  • AJAX is the art of exchanging data with the server and updating part of the web page without reloading the entire page.

  • It is a function of the default asynchronous execution mechanism. AJAX is divided into synchronous (async = false) and asynchronous (async = true)

What is a synchronization request? (false)

  • Synchronous request means that the browser cannot do anything after the current request is sent.
  • You must wait for the request to complete the return data before executing subsequent code.
  • It is equivalent to queuing in life. You have to wait for the first person to finish his own things before the latter can proceed.
  • In other words, when the JS code is loaded into the current AJAX, all the code in the page will stop loading, and the page will be in a suspended animation state.
  • When this AJAX is executed, it will continue to run other code pages to remove the suspended animation state

What is an asynchronous request? (Default: true)

  • Default asynchronous: When an asynchronous request is made, the browser can continue to do anything,
  • Ajax sending requests does not affect the loading of the page and the user's operation, which is equivalent to two lines, each going its own way, without affecting each other.
  • Generally the default value is true, asynchronous. Asynchronous requests can not affect the user experience at all,
  • Regardless of whether the request is long or short, users are concentrating on operating other content on the page and will not feel waiting.

Advantages of AJAX

  • No need for plug-in support, original js can be used
  • Good user experience (data can be updated without refreshing the page)
  • Reduce the burden of server and bandwidth
  • Disadvantages: search engine support is not enough, because the data is not on the page, search engines can’t search

AJAX operation process

Operating procedures:

  • First take out the data in the database through the PHP page
  • Take it out and convert it into a json format string, and then use ajax to return the string to the front desk
  • Then use json.parse to parse and add to the page through a loop
  • On the contrary, the front-end data can be submitted to the back-end using ajax
  • But there is no way to directly insert these data into the database in the background, so you must submit it to the PHP page first
  • Finally, PHP inserts the data into the database

Use of AJAX

  • There is a built-in constructor in js to create ajax objects
  • After creating the ajax object, we use the ajax object method to send requests and receive responses
  • One of the biggest features of Ajax is that it can transfer or read and write data to the server without refreshing the page (also known as updating the page without refreshing). This feature is mainly due to the XMLHTTPRequest object of the XMLHTTP component.

1. Create an ajax object

  • We use this xhr object to send ajax requests
const xhr = new XMLHttpRequest()

2. Configure link information

  • XMLHttpRequest object attribute description (used to exchange data with the server.)
  • After the code below is executed, the basic configuration information for this request is finished
const xhr = new XMLHttpRequest()
// The open method in the xhr object is to configure the request information
// The first parameter is the request method of this request get / post / put / ...
// The second parameter is the url of this request 
// The third parameter is whether the request is asynchronous or not, the default true means asynchronous, false means synchronous
// xhr.open('request mode','request address', is it asynchronous)
xhr.open('get', './data.php')

3. Send the request

  • The following code is to send the configured ajax object to the server
//To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object:
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
// Use the send method in the xhr object to send the request
xhr.send()
  • A most basic ajax request is the above three steps, but with the above three steps alone, we can indeed send the request to the server
  • If the server is normal, the response can be returned to the client, but we cannot get the response
    If we want to get a response, we need two prerequisites
  1. This HTTP request is successful, that is, the http status code we are going to say below is 200 ~ 299
  2. The ajax object also has its own status code to indicate the various stages in this ajax request

AJAX status code

  • ajax status code-xhr.readyState is used to indicate a certain state in the entire process of an ajax request
  • 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
  • At this time, we will find that in the entire process of an ajax request, only when readyState === 4
    , we can use the data provided by the server normally
  • So, with http status code 200 ~ 299
  • There is a member in an ajax object called xhr.status
  • This member records the http status code of this request

readyStateChange

  • There is an event in the ajax object called the readyStateChange event
  • This event is specifically used to monitor the change of the readyState value of the ajax object
  • In other words, as long as the value of readyState changes, the event will be triggered
  • So we will monitor whether the readyState of ajax reaches 4 in this event
   const xhr = new XMLHttpRequest() xhr.open('get', './data.php')
	xhr.send()
	xhr.onreadyStateChange = function () {
	// This event will be triggered every time the readyState changes
	// We are here to determine whether the value of readyState is 4
	// And is the status code of http 200 ~ 299
	if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
	// This means that the verification passed
	// We can get the content of the response from the server}
}

Carry parameters when sending requests using ajax

  • 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 ways of carrying parameters get and post
  • Compared with POST, GET is simpler and faster, and can be used in most cases.
  • However, use POST requests in the following situations:
  1. Unable to use cache file (update the file or database on the server)
  2. Send a large amount of data to the server (POST has no data limit)
  3. When sending user input containing unknown characters, POST is more stable and reliable than GET
  • Send a get request with parameters
  • The parameters of the get request can be spliced ​​directly after the url
const xhr = new XMLHttpRequest()
// Add a? Directly after the address, and then pass it in the form of key=value // Two data are separated by &
xhr.open('get', './data.php?a=100&b=200')
xhr.send()

In this way, the server can receive two parameters, one is a, the value is 100, the other is b, the value is 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
const xhr = new XMLHttpRequest() xhr.open('post', './data.php')
	// If you use an ajax object to send a post request, you must first set the content-type in the request header
	// Tell the server what kind of data format I gave you xhr.setRequestHeader('content-type','application/x-www-form- urlencoded')
	// When the request body is directly sent again, write it in ()
	// No question mark is needed, just the form of'key=value&key=value' xhr.send('a=100&b=200')
// 1. Create ajax object
let xhr = new XMLHttpRequest()
// 2. Configure request information xhr.open(‘GET’, ‘./test.php’, true)
// 3. Send request xhr.send()
// 4. Accept the response xhr.onload = function () {
console.log(xhr.responseText) }

Intelligent Recommendation

Python crawls Baidu pictures

Work needs to search a lot of facial expression data on the Internet! This idea came into being! Baidu image search first, just like in waterfall mode Use inspection elements to find:   Only the ...

Tensorflow model file ckpt parameter acquisition

Know the ckpt file of the model file, get the parameter names of the model through pywrap_tensorflow  ...

Connection and configuration of C3P0 and database

Import C3P0 JAR package first C3P0UTIL.JAVA is placed under Util package C3P0-config.xml is placed in the src directory c3p0-config.xml C3P0Util.java...

Lesson 5-5: How to package and deploy Spring Boot items

Spring Boot The use of embedded containers, so its deployment method has become very simple and flexible, you can use Spring Boot Item packaging Stand alone Jar or War It can be shipped as a package o...

git | git add ssh key

Scenes: Create a SSH Key: Open the ID_RSA.Pub file under the directory C: \ Users \ Lanfeiy.ssh, add the contents inside to gitlab, as shown below:...

More Recommendation

Initialization block, class initialization block (static code block), the order in which objects are created

Initialization block The strength initialization block is "illusion". After a class is compiled, the code block disappears and is restored to all the code of each constructor. Function: So t...

Spring WebSocket configuration instructions, method functions and execution order

Spring version 5.0 xml configuration Note: The front-end WS protocol can request /websocket configured in the root directory of the project, and the path configured in the blue part of the code block ...

4.JavaScript implementation table interlaced discoloration

The CSS code is as follows: HTML code is as follows The JS code is as follows:...

Hive and HBase table of data migration

Preamble: The company recently migrated data, do a test to verify the command. A, Hive section Two, HBase table  ...

Quick sort (refer to "Introduction to Algorithms", the core code is only 18 lines)

Preface Generally speaking, quick sort is an advanced insertion sort, but although many methods on the Internet are easy to understand, it is difficult to see the similarities with basic insertion sor...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top