dpmopn8542 2011-01-31 09:12
浏览 35

是否有非ajax方式重复轮询外部js文件?

would really appreciate any help with this JS question.
Have been experimenting for an hour or so now and haven't bumped into anything that does the trick.


Current Setup

  • Website 1: the 'content' site. This site displays different content depending on whether a user is logged into website 2 or not. I'm using a script tag in the head with the src set to a PHP file located on website 2.
  • Website 2: the 'user management' site. This uses PHP to output in a 'javascript' file whether a user is logged in (i.e. as a js var).


Currently this setup works fine for checking whether a user is logged into website 2 system when a user loads the page on website 1.

However, rather than a once-off check, I'm wanting the PHP file on website 2 to be polled every 2 seconds to see if the loggedin status has changed.

Is there a way to do this in vanilla javascript? (i.e. without ajax or jq - I'm trying to keep the whole system small and known).

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!)

  • 写回答

2条回答 默认 最新

  • doujia8801 2011-01-31 09:18
    关注

    I suppose you could create an interval function changing the src property of a script element in your page?

    setInterval(
      function(){
        myscript.src = '/urltophp?'+someRandomKey;
      }, 2000);
    

    Where someRandomKey prevents the script being cached in the browser. A script tag can have an id, so it's retrievable using document.getElementById

    To create a random key this may help:

    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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向