Detailed explanation of the use of Ajax and browser cache
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!

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

To remove FirefoxSnap in Ubuntu Linux, you can follow these steps: Open a terminal and log in to your Ubuntu system as administrator. Run the following command to uninstall FirefoxSnap: sudosnapremovefirefox You will be prompted for your administrator password. Enter your password and press Enter to confirm. Wait for command execution to complete. Once completed, FirefoxSnap will be completely removed. Note that this will remove versions of Firefox installed via the Snap package manager. If you installed another version of Firefox through other means (such as the APT package manager), you will not be affected. Go through the above steps

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.

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.

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

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.

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.
