Eliminate Caching


One of the stickiest problems when you’re developing your own Ajax applications is browser caching. Caching takes place when the browser, especially Internet Explorer, has already visited a URL; it stores a copy of the response from the server and doesn’t actually access the URL again directly.

That can be maddening when you’re changing the output of, say, a PHP script and want the browser to read the new data sent back by that script. Say for example that you’re accessing javascript.php in this example earlier in the chapter:

 <body>   <H1>Reading JavaScript with Ajax</H1>   <form>     <input type = "button" value = "Get the JavaScript"       onclick = "getData('javascript.php)">   </form>   <div >     <p>The data will go here.</p>   </div> </body>

If you’re debugging javascript.php, you want the browser to keep reading data from it. But, because it has cached javascript.php, it doesn’t; you keep getting your old data, time after time. How can you fix this? The most popular solution among Ajax programmers is to modify the URL itself with some nonsense data; because the browser hasn’t seen that URL before, it’ll go back to the server rather than the cache to update the data from that URL. For example, you could just add ?r=6 to the end of the javascript.php relative URL like this:

 <body>   <H1>Reading JavaScript with Ajax</H1>   <form>     <input type = "button" value = "Get the JavaScript"       onclick = "getData('javascript.php?r=6')">   </form>   <div >     <p>The data will go here.</p>   </div> </body>

The r parameter isn’t used by javascript.php, but including it changes the URL enough so that the browser thinks that javascript.php is a different URL from javascript.php?r=6, and so doesn’t go to the cache for data but instead accesses the URL directly.

That’s fine for debugging purposes because you can keep updating the r parameter’s value, creating new URLs. But what about a for-release version of your code? If caching is a problem, that is, if you need to keep going back to a server-side script that’s going to send you new data, you can use the current time as an URL parameter, like this:

 <body>   <H1>Reading JavaScript with Ajax</H1>   <form>     <input type = "button" value = "Get the JavaScript"       onclick = "getData('javascript.php?r=' +         new Date().getTime())">   </form>   <div >     <p>The data will go here.</p>   </div> </body>



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

Similar book on Amazon
HTML, XHTML, and CSS Bible
HTML, XHTML, and CSS Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
PHP and MySQL Web Development (4th Edition)
PHP and MySQL Web Development (4th Edition)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net