You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免JSON文件缓存,确保网页加载最新数据?

解决JSON文件更新后浏览器缓存问题

问题描述

服务器上的wg_data.json文件每5分钟通过PHP脚本更新,但网站刷新时仍显示缓存的旧数据,必须强制刷新才能看到最新内容。已添加<meta http-equiv="Expires" CONTENT="0">标签,但问题未解决。


现有代码

页面头部Meta标签

<meta http-equiv="Expires" CONTENT="0">

前端数据加载函数

let buildings = [];

async function getWG() {
    let updated = await fetch('cron_log.txt');
    updated = await updated.text();
    let updateText = document.getElementById("updated");
    updateText.innerHTML = '';
    updateText.innerHTML = 'Updated: ' + updated + ' EST';
    console.log(updated);
    if(buildings.length < 1){
        let response = await fetch('wg_data.json');
        buildings = await response.json();  
        buildings.sort(function (a, b) {
            return a.fee - b.fee;
        });
    }
    
    let element = document.getElementById("mainData");
    element.innerHTML = '';
    
    // 遍历建筑数组
    for (var x = 0; x < buildings.length; x++){
        if(!buildings[x].closed){
            let row = '<div class="row"><div class="col community">' + buildings[x].community + '</div><div class="col landid">' + buildings[x].landId + '</div><div class="col type">' + buildings[x].type + '</div><div class="col fee">' + (buildings[x].fee + 1000) + '</div><div class="col rank">' + buildings[x].rank + '</div></div>';
            element.innerHTML += row;     
        }
    }
}

后端PHP更新脚本(片段)

$curl = curl_init();
$url = "test.com";

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);
$data = json_decode($response,true);

解决方案

1. 修复前端缓存逻辑(核心问题)

原代码中if(buildings.length < 1)的判断会导致仅第一次加载时获取JSON,后续调用getWG都复用内存中的旧数据,这是刷新看不到新数据的关键原因。同时,给JSON请求添加动态参数破弃浏览器缓存:

修改后的前端函数:

let buildings = [];

async function getWG() {
    let updated = await fetch('cron_log.txt');
    updated = await updated.text();
    let updateText = document.getElementById("updated");
    updateText.innerHTML = 'Updated: ' + updated + ' EST';
    console.log(updated);

    // 每次都请求最新JSON,用更新时间作为参数避免缓存
    let response = await fetch(`wg_data.json?t=${updated.replace(/\s/g, '')}`);
    buildings = await response.json();  
    buildings.sort(function (a, b) {
        return a.fee - b.fee;
    });

    let element = document.getElementById("mainData");
    element.innerHTML = '';
    
    // 遍历渲染逻辑不变
    for (var x = 0; x < buildings.length; x++){
        if(!buildings[x].closed){
            let row = '<div class="row"><div class="col community">' + buildings[x].community + '</div><div class="col landid">' + buildings[x].landId + '</div><div class="col type">' + buildings[x].type + '</div><div class="col fee">' + (buildings[x].fee + 1000) + '</div><div class="col rank">' + buildings[x].rank + '</div></div>';
            element.innerHTML += row;     
        }
    }
}

2. 后端设置HTTP缓存头(彻底禁用静态文件缓存)

仅靠meta标签无法完全控制浏览器缓存,需通过服务器配置或PHP脚本给JSON文件发送禁用缓存的响应头:

方式一:服务器配置(推荐)
  • Nginx:在站点配置中添加:
location ~* \.json$ {
    add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0";
    add_header Pragma "no-cache";
    add_header Expires "Thu, 01 Jan 1970 00:00:00 GMT";
}
  • Apache:在.htaccess文件中添加:
<FilesMatch "\.json$">
    Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
    Header set Pragma "no-cache"
    Header set Expires "Thu, 01 Jan 1970 00:00:00 GMT"
</FilesMatch>
方式二:改用PHP接口返回JSON

如果允许修改请求方式,可将JSON文件改为PHP接口(如wg_data.php),直接输出数据并设置缓存头:

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header("Content-Type: application/json");

echo file_get_contents('wg_data.json');
?>

前端请求时改为fetch('wg_data.php')即可。

3. 定时自动刷新数据

既然JSON每5分钟更新,可让前端自动定时拉取最新数据,无需用户手动刷新:

// 页面加载时执行一次
getWG();
// 每5分钟(300000毫秒)自动刷新
setInterval(getWG, 300000);

内容的提问来源于stack exchange,提问作者mickdeez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:25:18