Table of Contents
Ajax 异步编程
Ajax 概述
Home Web Front-end JS Tutorial Understand the basics of Ajax data request

Understand the basics of Ajax data request

Sep 11, 2020 pm 04:38 PM
ajax data request

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

What are the ajax versions? What are the ajax versions? Nov 22, 2023 pm 02:00 PM

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles