我有外部 js 文件,通过使用 ajax 请求运行 home.php 文件。
我的代码中一切都很好。但是即使我在url中添加随机函数,缓存也不清楚。
这是我的js代码。
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://myurl/home.php?t="+Math.random(),true);
xmlhttp.setRequestHeader( "Pragma", "no-cache" );
xmlhttp.setRequestHeader( "Cache-Control", "no-cache" );
xmlhttp.send();
每次我从index.php调用这个js文件时,我都会得到缓存结果。
为了避免缓存问题,我已经在 url 中添加了唯一的 id。但这不起作用。所以,请给我任何解决这个问题的建议。
最佳答案
为了避免 js
或 css
文件包含缓存问题(在问题评论中回答您的问题),您必须在每次更改后自动更改它们的包含链接,为此您可以在 html
中的资源包含步骤中使用 filemtime("file")
filemtime
返回文件创建时间,在此处查找有关 - http://php.net/manual/en/function.filemtime.php 的手册
<script
src="http://url/some.js?t=<?php filemtime("PATH_TO_FILE/some.js") ?>" >
</script>
<link rel="stylesheet" type="text/css"
href="http://url/some.css?t=<?php filemtime("PATH_TO_FILE/some.css") ?>" >
因此,通过这种方式,在每次修改 some.js
或 some.css
时,它们的创建时间都会改变,并更改为您的 home.php
将向该资源添加新的 url 链接 (http://url/some.js?t=14....
),并且 Bowser 必须再次加载它们
关于javascript - 为什么ajax请求时缓存不清晰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34353471/