I'm currently using below method to call an external php file with some variables using javascript
<script src="http://www.domain.com/function.php?param=A" type="text/javascript"></script>
And the code in the function.php file will return data in Javascript format, something like
<?php Header("content-type: application/x-javascript");
$p = $_GET['param'];
$r = mt_rand(0, 10);
echo "document.write('" . $p . $r . "');";
?>
This is just a simple example. My problem is on Google Chrome (v19), if the page had not finished loaded, the random number will not be random when I keep refreshing. It will become truly random only when I hit the refresh button AFTER the page finished load. Why is this happen and how can I solve it?
I tested on Firefox 12 and IE8, even if I refresh the page before it finished load, the random number will always be regenerated.
Your URL's query string says param=A
, you're referencing $_GET['param1']
on your PHP/JS file. Shouldn't it be $_GET['param']
?
You'll probably want to add the headers so that your js file is not cached
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
You need a small JS hack. Basically, you want to dynamically add the <script>
tag in JS and add a random parameter at the end of the URL.
var hookScripts = function(url, src) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = url || null;
s.innerHTML = src || null;
document.getElementsByTagName("head")[0].appendChild(s);
};
hookScripts('http://www.domain.com/function.php?param=A&randomSalt=' + Math.random());
This will force chrome to request the JS file again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.