我怎样才能强行打开窗户.位置来发出HTTP请求,而不是使用缓存

How can I force window.location to make an HTTP request instead of using the cache?

本文关键字:请求 HTTP 缓存 位置 窗户 开窗      更新时间:2023-09-26

在我的web应用程序中,我将window.location设置为导航到另一个页面,但由于某些原因,Firefox显示的是该页面的旧版本。

使用Firebug我检测到浏览器甚至没有发送HTTP请求,它只是使用该页面的旧版本(甚至不是最后一个)并显示它。

页面本身有所有常见的标题来防止缓存,当我使用链接或手动输入浏览页面时,缓存工作完美。

设置window.location时才会出现此问题。

这是Firefox的问题还是其他浏览器的问题?这种行为可以改变吗?

您可以在页面URL中添加一个随机参数,以便浏览器发出新的请求。

所以不用

 window.location = "my.url/index.html";
使用

 window.location = "my.url/index.html?nocache=" + (new Date()).getTime();

可以使用location。使用true参数重新加载,该参数将始终绕过缓存。

window.location.reload(true);

在url中添加一些特定于时间或随机的查询字符串值。这将强制重新加载页面。

var yourNewLoc = "http://newlocation.com/";
document.location = yourNewLoc + "?c=" + (new Date()).valueOf();

您必须验证url中是否存在任何现有的查询参数。如果存在任何查询参数,则应该使用"&"附加时间戳。我写了一个简短的片段,可能会对你有所帮助。

window.newLocation = function( location ) {
    var newLocation = ( typeof location === "string" ) ? location : window.location.href,
       appendType = ( newLocation.indexOf("?") < 0 ) ? "?" : "&";
    window.location = newLocation + appendType + "_t=" + (new Date()).getTime();
}

用法:

newLocation("index.html") or window.newLocation("index.html") 
// opens "index.html?_t=<timstamp>"
newLocation("index.html?existingQuery=true") or window.newLocation("index.html?existingQuery=true") 
// opens "index.html?existingQuery=true&_t=<timstamp
newLocation() or window.newLocation() 
// opens existing window location with a timestamp

您可以进一步修改代码片段,以删除查询参数中现有的时间戳,以避免重复

只需要告诉你的下载函数(在控制器中,在Laravel的情况下)不要通过设置标题来缓存它,使用下面的Laravel代码:

$headers =[
            'Content-Type' => 'application/text',
            'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
            'Cache-Control' => 'post-check=0, pre-check=0, false',
             'Pragma' => 'no-cache',  ];
return response()->file($pathToFile, $headers);

这段代码非常适合PhP,只需要相应地转移代码。通过添加新的日期可能会使链接无效,特别是如果你使用临时签名链接等。

欢呼