Prevent ajax response caching

I just started working with HTML and java script. I am stuck between them. I created one web page that reads data from XML and displays on the page. I can do it successfully. But if I modify the XML data and update the browser, it does not reflect the updated data on my web page. If I clear the browser history manually and then refresh the page, it will display the updated data. But I want the data to be updated as soon as I refresh the page. I don’t want to clear my browser history every time.

My server is an Apache server.

My html code is:

<!DOCTYPE HTML PUBLIC "- HTML 4.0 Transitional//EN"> <html> <TITLE>DynamicHTML Page</TITLE> <META content="text/html; charset=windows-1252" http-equiv=Content-Type> <META http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <META http-equiv="refresh" content="10";> <META name=Author content=""> <META name=Keywords content=""> <body> </div> <xml ID="noteXML" SRC="note.xml"></xml> <script> function ReadXML() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","note.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("data").innerHTML= xmlDoc.getElementsByTagName("data")[0].childNodes[0].nodeValue; document.getElementById("status").innerHTML= xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue; } </script> <div> <b>Require Data :</b> <span id="data"></span><br /> <div> <b>Current Status:</b> <span id="status"></span><br /> <script> ReadXML(); </script> </body> </html> 

My XML:

 <?xml version="1.0" encoding="ISO-8859-1"?> <note> <data> 450 </data> <status> Reading Data From XML </status> </note> 

I also tried to make sure that the browser does not create a cache, but nothing works.

 <META http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <META http-equiv="refresh" content="10";> 
+4
source share
1 answer

You can add a random number to the file:

 xmlhttp.open("GET","note.xml?" + Math.random(),false); 

This ensures that the browser will always receive the latest version, because it will never cache, find a cached version that matches the random one.

+2
source

Source: https://habr.com/ru/post/1491578/


All Articles