Home > Web Front-end > JS Tutorial > body text

How to Prevent Browser Caching for AJAX Responses?

Patricia Arquette
Release: 2024-11-17 14:56:02
Original
993 people have browsed it

How to Prevent Browser Caching for AJAX Responses?

How to Disable Browser Caching for AJAX Responses

When loading dynamic content with AJAX, such as using jQuery's $.get() method, the results may be cached by the browser. This can lead to stale data being displayed when subsequent requests are made.

Hack: Adding Random QueryString

A common workaround is to append a random string to the query string, effectively making each request unique and thus preventing caching. However, this approach is not ideal due to its hacky nature.

Better Solution: $.ajaxSetup

A more elegant way to disable browser caching for AJAX requests is to use the $.ajaxSetup() function. By setting the cache option to false, all future AJAX calls, regardless of the method used (e.g., $.get, $.ajax), will have caching disabled.

$.ajaxSetup({ cache: false });
Copy after login

Once this configuration is set, all AJAX requests made within the scope of the current document will automatically have their cache disabled.

Additional Tips

If a unique string is still required to prevent caching for specific situations, consider using a unique number sequence or a hashed value based on the request parameters. This provides a more deterministic and readable approach compared to using new Date().toString().

The above is the detailed content of How to Prevent Browser Caching for AJAX Responses?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template