This time I will bring you a detailed explanation of the use of Ajax and browser caching. What are the precautions when using Ajax and browser caching? The following is a practical case, let's take a look.
In modern web applications, the front-end code is flooded with a large number of Ajax requests. If the browser cache can be used for Ajax requests, the network requests can be significantly reduced and the program response speed can be improved.
1. Ajax Request
Using the jQuery framework can make Ajax requests very conveniently. The sample code is as follows:
$.ajax({ url : 'url', dataType : "xml", cache: true, success : function(xml, status){ } });
is very simple, pay attention to the 4th line of code: cache: true, which explicitly requires that if the current request has a cache, use the cache directly. If this property is set to false, it will request the server every time. Jquery's Comments are as follows:
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
There is only so much work on the front end, so can Ajax requests take advantage of the browser cache?
Keep watching.
2. Http protocol
The header part of the Http protocol defines whether the client should do Cache and how to do Cache. For details, see 14.9 Cache-Control and 14.21 Expires of Http Header Field Definitions. Here is a brief explanation:
Cache-Control
Cache-control is used to control HTTP cache (it may not be partially implemented in HTTP/1.0, only Pragma is implemented: no-cache)
Format in the data packet:
Cache-Control: cache-directive
cache-directive can be the following:
Use when requesting:
| "no-cache"
| "no-store"
| "max-age" "=" delta- seconds
| "max-stale" [ "=" delta-seconds ]
| "min-fresh" "=" delta-seconds
| "no-transform"
| "only-if -cached"
| "cache-extension"
response is used:
| "public"
| "private" [ "= " field-name ]
| "no-cache" [ "=" field-name ]
| "no-store "
| "no-transform"
| "must-revalidate"
| "proxy-revalidate"
| "max-age" "=" delta-seconds
| "s- maxage" "=" delta-seconds
| "cache-extension"
Description:
-Public indicates that the response can be cached by any cache area.
-Private Indicates that all or part of the response message for a single user cannot be sharedCache processing. This allows the server to describe only a partial response from a user that is not valid for other users' requests.
-no-cache indicates that the request or response message cannot be cached (HTTP/1.0 is replaced by Pragma's no-cache)
-no-store is used to prevent important information from being released unintentionally. Sending it in the request message will cause both the request and response messages to use caching.
-max-age Indicates that the client can receive responses with a lifetime no greater than the specified time in seconds.
-min-fresh Indicates that the client can receive responses with a response time less than the current time plus the specified time.
-max-stale Indicates that the client can receive response messages beyond the timeout period. If the value of max-stale message is specified, then the client can
receive response messages that exceed the specified value of the timeout period.
Expires
Expires represents the effective time of Cache, allowing the client not to send requests before this time, which is equivalent to the effect of max-age. But if they exist at the same time, they will be overridden by Cache-Control's max-age.
Format: Expires = "Expires" ":" HTTP-date
Example: Expires: Thu, 01 Dec 1994 16:00:00 GMT
Last-Modified
Last-Modified用GMT格式表明了文档的最后修改时间,客户端第二次请求此URL时,会在头部加入一个属性,询问该时间之后文件是否有被修改过。如果服务器端的文件没有被修改过,则返回状态是304,内容为空,这样就节省了传输数据量。
3. 我的问题
这几天在做Web前端的时候,发现客户端的每次Ajax都会从服务器端请求数据,而这些数据的即时性没有那么高,没必要每次都请求。
在显式的给Ajax加上cache为true后,发现问题依旧。于是怀疑是服务端的问题,服务端使用 jersey 搭建了基于Restful的服务,代码片段如下:
@GET @Produces("application/xml") public Response getProducts() { Response.ResponseBuilder response = Response.ok(data); return response.build(); }
添加Cache控制后,进行测试,一切OK。
最后的代码如下:
@GET @Produces("application/xml") public Response getProducts() { Response.ResponseBuilder response = Response.ok(data); // Expires 3 seconds from now..this would be ideally based // of some pre-determined non-functional requirement. Date expirationDate = new Date(System.currentTimeMillis() + 3000); response.expires(expirationDate); return response.build(); }
以上只是示例代码,还可以进行更精细的控制,例如使用CacheControl、Last-Modified等等。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of Ajax and browser cache. For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
