Reload JSON file with jQuery on update page

I am trying to do the following:

$.getJSON(sampleJson.json), function(data) {}

Reading data from sampleJson.jsonon a web page. The data displayed changes on a web page sent via an AJAX call, as shown below:

$.ajax({type: "GET", url: "...", data: "abc" ,
    Success: function(data) {}

The data is taken on the server side, where I used the servlet to receive the data. Here lies the problem, I am writing data in the same sampleJson.jsonway to update the json file. Now I want the changed data to be displayed on the web page when the page is refreshed, since I use the same one sampleJson.jsonto display the data when the page loads, but the web page does not display the changed data.

I hope the problem is clear, is there a way to solve this problem?

+4
source share
2 answers

This is because caching content comes from the second request. Add a timestamp parameter using the json url, which will make the http request new for every request. As below

 var curTimeStamp = Math.floor(Date.now() / 1000);
 $.ajax({type: "GET", url: "/json/sampleJson.json?t="+curTimeStamp, data: "abc" ,
Success: function(data) {}
0
source

If you can change the server serving the json file, you can add a no-cache header.

Doing this in nodejs-expressjs

..
res.setHeader('Cache-Control', 'no-cache');
res.json(yourdata);
..

but how it will depend on your serveride technology and the possibility of changing it. (Java?)

0
source

All Articles