[英]Loads external php file with javascript src
I'm currently using below method to call an external php file with some variables using javascript 我目前正在使用以下方法使用javascript使用一些变量来调用外部php文件
<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 而且function.php文件中的代码将以Javascript格式返回数据,例如
<?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.
我的问题是在Google Chrome(v19)上,如果页面尚未完成加载,则当我不断刷新时,随机数将不会是随机的。 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. 我在Firefox 12和IE8上进行了测试,即使在加载完成之前刷新页面,也始终会重新生成随机数。
Your URL's query string says param=A
, you're referencing $_GET['param1']
on your PHP/JS file. 您网址的查询字符串为
param=A
,您在PHP / JS文件中引用$_GET['param1']
。 Shouldn't it be $_GET['param']
? 应该不是
$_GET['param']
吗?
You'll probably want to add the headers so that your js file is not cached 您可能需要添加标题,以便不缓存您的js文件
<?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
?>
See http://php.net/manual/en/function.header.php 参见http://php.net/manual/en/function.header.php
You need a small JS hack. 您需要一个小的JS技巧。 Basically, you want to dynamically add the
<script>
tag in JS and add a random parameter at the end of the URL. 基本上,您想在JS中动态添加
<script>
标记,并在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. 这将迫使chrome重新请求JS文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.