防止浏览器缓存AJAX请求 [英] Prevent browser from caching AJAX requests

查看:244
本文介绍了防止浏览器缓存AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了一个应用程序,它在Opera和Firefox上都可以正常运行,但是在Google Chrome上,它可以缓存AJAX请求并提供陈旧数据!

I've setup an app and it works fantastic on Opera and Firefox, but on Google Chrome it caches the AJAX request and will give stale data!

http://gapps.qk.com.au 是应用程序。在Chrome中运行时,它甚至不会发送AJAX请求,但在其他浏览器中尝试时,它始终会发出AJAX请求并返回数据。

http://gapps.qk.com.au is the app. When ran in Chrome it doesn't even send the AJAX requests, but when tried in another browser it always does the AJAX request and returns data.

是否存在是否有任何方法(Apache / PHP / HTML / JS)阻止Chrome执行此行为?

AJAX调用:

function sendAjax(action,domain,idelement) {

                    //Create the variables
                var xmlhttp,
                    tmp,
                    params = "action=" + action
                             + "&domain=" + encodeURIComponent(domain)

                    xmlhttp = new XMLHttpRequest(); 
                //Check to see if AJAX request has been sent
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                        $('#'+idelement).html(xmlhttp.responseText);
                    }
                };
                xmlhttp.open("GET", "ajax.php?"+params, true);
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //console.log(params);
                xmlhttp.send(params);

            }
sendAjax('gapps','example.com','gapps');


推荐答案

浏览器缓存在不同设置下的行为不同。您不应依赖用户设置或用户的浏览器。也可以使浏览器也忽略标题。

The browser cache behaves differently on different settings. You should not depend on user settings or the user's browser. It's possible to make the browser ignore headers also.

有两种防止缓存的方法。

There are two ways to prevent caching.

->将AJAX请求更改为POST。浏览器不会缓存POST请求。

--> Change AJAX request to POST. Browsers don't cache POST requests.

-> Better Way&好的方法:使用当前时间戳或任何其他唯一数字向您的请求添加一个附加参数。

--> Better Way & good way: add an additional parameter to your request with either the current time stamp or any other unique number.

params = "action=" + action 
         + "&domain=" + encodeURIComponent(domain) 
         + "&preventCache="+new Date();

这篇关于防止浏览器缓存AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆