我有一个PHP脚本来删除csv文件的旧实例并上传一个新的和一个javascript函数来读取该文件。它工作正常,直到我添加了PHP删除旧文件,现在由于某种原因javascript函数总是取出相同的文件,即使它被更改。
我已经进入并检查了data.csv文件,它是新文件,但该函数仍然取出旧文件。如果我手动删除该文件,该功能仍然神秘地访问data.csv文件...即使它被删除。
这是php:
<?php
if(file_exists('upload/data.csv'))
{
unlink('upload/data.csv'); // deletes file
}
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, 'upload/data.csv');
?>
这是javascript。注意:即使data.csv已更改或被删除,变量“allText”也将始终是旧CSV文件的内容。
function LoadCSV(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
我不确定为什么会这样或者如何修复它?
答案 0 :(得分:3)
这可能是浏览器缓存。 我喜欢在网址中使用随机值来诱骗浏览器认为它是一个不同的页面:
试试这个:
function LoadCSV() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv?nocache="+(Math.random()+'').replace('.',''), true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
get参数nochache对服务器或浏览器没有任何意义,但是每次都会愚弄它以获取新资源,但代价是完全失去浏览器缓存。从技术上讲,两次获得相同的值是可能的(虽然极不可能),所以如果你想让它完全万无一失,你可以用毫秒或者其他东西来增加时间。
请注意,这也会绕过几乎所有其他类型的缓存。