Understand the basics of Ajax data request
##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.Recommended related articles: ajax video tutorial
Ajax application scenarios
Pull up the page to load more dataAjax operating principle and implementationPaging without refreshing the list data
Form item leaves focus data verification
Search box prompt text drop-down list
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.
Ajax implementation steps
- Create Ajax object
-
var xhr = new XMLHttpRequest();
Copy after login
- Tell Ajax the request address and request Method
-
xhr.open('get', 'http://www.example.com');
Copy after login
- Send a request
-
xhr.send();
Copy after login
- Get the response data from the server to the client
-
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对象
Request parameter passing
Traditional website form submissionxhr.open('get', 'http://www.example.com?name=zhangsan&age=20');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send('name=zhangsan&age=20');
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.
Format of request parameters
- application/x-www-form-urlencoded
-
name=zhangsan&age=20&sex=男
Copy after login
- application/json
-
{name: 'zhangsan', age: '20', sex: '男'}
Copy after login
JSON.stringify() // 将json对象转换为json字符串
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 usedxhr.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); } }
The difference between two ways of obtaining server-side response
Ajax error handling
- 网络畅通,服务器端能接收到请求,服务器端返回的结果不是预期结果。
可以判断服务器端返回的状态码,分别进行处理。xhr.status 获取http状态码 - 网络畅通,服务器端没有接收到请求,返回404状态码。
检查请求地址是否错误。 - 网络畅通,服务器端能接收到请求,服务器端返回500状态码。
服务器端错误,找后端程序员进行沟通。 - 网络中断,请求无法发送到服务器端。
会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。
低版本 IE 浏览器的缓存问题
问题:在低版本的 IE 浏览器中,Ajax 请求有严重的缓存问题,即在请求地址不发生变化的情况下,只有第一次请求会真正发送到服务器端,后续的请求都会从浏览器的缓存中获取结果。即使服务器端的数据更新了,客户端依然拿到的是缓存中的旧数据。
解决方案:在请求地址的后面加请求参数,保证每一次请求中的请求参数的值不相同。
xhr.open('get', 'http://www.example.com?t=' + Math.random());
Ajax 异步编程
Ajax 封装
问题:发送一次请求代码过多,发送多次请求代码冗余且重复。
解决方案:将请求代码封装到函数中,发请求时调用函数即可。
ajax({ type: 'get', url: 'http://www.example.com', success: function (data) { console.log(data); } })
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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 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

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:

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.

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.

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.
