非常感谢您对这个 JS 问题的任何帮助。
现在已经试验了一个小时左右,但还没有遇到任何有效的方法。
当前设置
- 网站 1:“内容”网站。该站点根据用户是否登录网站 2 显示不同的内容。我在 head 中使用脚本标记,并将 src 设置为位于网站 2 上的 PHP 文件。
- 网站 2:“用户管理”网站。这使用 PHP 在“javascript”文件中输出用户是否登录(即作为 js 变量)。
但是,我希望每 2 秒轮询一次网站 2 上的 PHP 文件,以查看登录状态是否已更改,而不是一次性检查。
有没有办法在普通的 JavaScript 中做到这一点? (即没有 ajax 或 jq - 我试图保持整个系统小而已知)。
If it's relevant, a friend suggested putting a randomly generated variable at the end of the PHP file name to prevent caching. (He didn't know how it could be repeatedly polled though!)
最佳答案
我想您可以创建一个间隔函数来更改页面中脚本元素的 src
属性?
setInterval(
function(){
myscript.src = '/urltophp?'+someRandomKey;
}, 2000);
其中 someRandomKey
阻止脚本缓存在浏览器中。 script
标记可以有一个 id
,因此可以使用 document.getElementById
要创建随 secret 钥,这可能会有所帮助:
function randomKey(iLen) {
var sKey = ''
, isKey = ''
, i = 0
, aRanges = ['48,9', '65,25', '97,25'];
iLen = !iLen ? 4 : iLen;
while (i < iLen) {
var aRange = String(aRanges[Math.round(Math.random() * 2)]).split(',');
isKey += String(aRanges[Math.round(Math.random() * 2)]) + ',';
sKey += String.fromCharCode(Math.round(parseInt(aRange[0], 10) +
(Math.random() * parseInt(aRange[1], 10))));
i++;
}
return sKey;
}
关于php - 有没有非ajax的方式来重复轮询外部js文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4849151/