Home > Web Front-end > JS Tutorial > body text

Understand the basics of Ajax data request

coldplay.xixi
Release: 2020-09-11 17:32:01
forward
1587 people have browsed it

Understand the basics of Ajax data request

Recommended related articles: ajax video tutorial

##Ajax Overview

It is a set of methods provided by the browser, which can update data without page refresh and improve the user's experience of browsing website applications.

Ajax application scenarios

Pull up the page to load more data

Paging without refreshing the list data
Form item leaves focus data verification
Search box prompt text drop-down list

Ajax operating principle and implementation

Ajax operating principle Ajax is equivalent to the browser sending requests and receiving responses Agent to partially update page data without affecting the user's browsing of the page, thereby improving the user experience.

Understand the basics of Ajax data request
Ajax implementation steps

    Create Ajax object
  1.  var xhr = new XMLHttpRequest();
    Copy after login
    Tell Ajax the request address and request Method
  1. xhr.open('get', 'http://www.example.com');
    Copy after login
    Send a request
  1.  xhr.send();
    Copy after login
    Get the response data from the server to the client
  1. xhr.onload = function () {
         console.log(xhr.responseText);
     }
    Copy after login

Server-side response data format In real projects, the server-side will use JSON objects as the response data format in most cases. When the client gets the response data, it needs to splice the JSON data and HTML string, and then display the spliced ​​result on the page.
In the process of http request and response, whether it is request parameters or response content, if it is an object type, it will eventually be converted into an object string for transmission.

JSON.parse() // 将 json 字符串转换为json对象
Copy after login

Request parameter passing

Traditional website form submission

Copy after login
             
 GET request method

xhr.open('get', 'http://www.example.com?name=zhangsan&age=20');
Copy after login
POST request method

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send('name=zhangsan&age=20');
Copy after login

Request message The data block passed during the HTTP request and response is called a message, including the data to be transmitted and some additional information. These data and information must comply with regulations. format.

Understand the basics of Ajax data request
Format of request parameters

    application/x-www-form-urlencoded
  1.  name=zhangsan&age=20&sex=男
    Copy after login
    application/json
  1. {name: 'zhangsan', age: '20', sex: '男'}
    Copy after login
Specify the value of the Content-Type attribute in the request header to be application/json, telling the server that the format of the current request parameter is json.

JSON.stringify() // 将json对象转换为json字符串
Copy after login
Note: The get request cannot submit the json object data format, and the form submission of traditional websites does not support the json object data format.

Get the server-side response

Ajax status code After creating the ajax object, configuring the ajax object, sending the request, and receiving the server-side response data , each step in this process will correspond to a value, and this value is the ajax status code.

0: The request has not been initialized (open() has not been called yet)

1: The request has been established, but has not been sent (send() has not been called yet)
2: The request has been Send
3: The request is being processed, usually some data in the response is available
4: The response has been completed, the server's response can be obtained and used

xhr.readyState // 获取Ajax状态码
Copy after login

onreadystatechange event

This event will be automatically triggered when the Ajax status code changes.

The Ajax status code can be obtained and judged in the event processing function. When the status code is 4, the server-side response data can be obtained through xhr.responseText.

// 当Ajax状态码发生变化时
 xhr.onreadystatechange = function () {
     // 判断当Ajax状态码为4时
     if (xhr.readyState == 4) {
         // 获取服务器端的响应数据
         console.log(xhr.responseText);
     }
 }
Copy after login

The difference between two ways of obtaining server-side response
Understand the basics of Ajax data request
Ajax error handling

  1. 网络畅通,服务器端能接收到请求,服务器端返回的结果不是预期结果。
    可以判断服务器端返回的状态码,分别进行处理。xhr.status 获取http状态码
  2. 网络畅通,服务器端没有接收到请求,返回404状态码。
    检查请求地址是否错误。
  3. 网络畅通,服务器端能接收到请求,服务器端返回500状态码。
    服务器端错误,找后端程序员进行沟通。
  4. 网络中断,请求无法发送到服务器端。
    会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。

低版本 IE 浏览器的缓存问题
问题:在低版本的 IE 浏览器中,Ajax 请求有严重的缓存问题,即在请求地址不发生变化的情况下,只有第一次请求会真正发送到服务器端,后续的请求都会从浏览器的缓存中获取结果。即使服务器端的数据更新了,客户端依然拿到的是缓存中的旧数据。

解决方案:在请求地址的后面加请求参数,保证每一次请求中的请求参数的值不相同。

 xhr.open('get', 'http://www.example.com?t=' + Math.random());
Copy after login

Ajax 异步编程

Ajax 封装

问题:发送一次请求代码过多,发送多次请求代码冗余且重复。
解决方案:将请求代码封装到函数中,发请求时调用函数即可。

ajax({ 
     type: 'get',
     url: 'http://www.example.com',
     success: function (data) { 
         console.log(data);
     }
 })
Copy after login

Ajax 概述

它是浏览器提供的一套方法,可以实现页面无刷新更新数据,提高用户浏览网站应用的体验。

Ajax 的应用场景

页面上拉加载更多数据
列表数据无刷新分页
表单项离开焦点数据验证
搜索框提示文字下拉列表

相关学习推荐:javascript视频教程

The above is the detailed content of Understand the basics of Ajax data request. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!