##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();
- Tell Ajax the request address and request Method
-
xhr.open('get', 'http://www.example.com');
- Send a request
-
xhr.send();
- Get the response data from the server to the client
-
xhr.onload = function () { console.log(xhr.responseText); }
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 submission GET request methodxhr.open('get', 'http://www.example.com?name=zhangsan&age=20');POST request method
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=男
- application/json
-
{name: 'zhangsan', age: '20', sex: '男'}
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状态码
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

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