【问题标题】:try to open a page every 10 seconds尝试每 10 秒打开一个页面
【发布时间】:2010-01-15 06:01:44
【问题描述】:

使用 Javascript(或 Ajax)我想每 10 秒连接到一个页面(一个 .php 页面)。这将在网页的用户端(浏览器)中完成。只是,我正在尝试查看在线用户。我的个人网站每天大约有 1-2 位访问者。

【问题讨论】:

标签: php javascript ajax post request


【解决方案1】:

使用jQuery$.post()方法:

setInterval(function(){
  $.post("getCount.php", function(result) {
    // do something with result
  }, "html");
}, 10000);

我假设您有充分的理由查询您自己的本地脚本。如果您想了解有关谁在访问您的网站、何时以及从何种环境(机器、浏览器等)访问您的网站的详细信息,我建议您考虑实现类似 Google Analytics 的内容。

【讨论】:

    【解决方案2】:

    此 Javascript 将每 10 秒读取一次页面 usersonline.php 并将内容放置到当前网页上。

    <html>
    <head>
    <script>
    
    var xmlrequest;
    
    function gotnewdata()
    {
        if(xmlrequest.readyState == 4)
        {
            document.getElementById("output").innerHTML = xmlrequest.responseText;
            setTimeout("loadpage();", 10000);
        }   
    }
    
    function loadpage()
    {
        xmlrequest = new XMLHttpRequest();
        xmlrequest.open("GET", "usersonline.php", true);
        xmlrequest.onreadystatechange = gotnewdata;
        xmlrequest.send(null);
    }
    
    </script>
    </head>
    <body onload="loadpage();">
    <h1>My Page</h1>
    <p>USERS ONLINE:</p><p id="output"></p>
    </body></html>
    

    【讨论】:

    • 这存在三个问题。 1) 内联事件附件是错误的形式并且存在问题,2) 将实际函数传递给 setTimeout 而不是字符串是可取的,因为它不涉及隐式 eval,并且 3) 这在 IE 中不起作用,因为XMLHttpRequest 在那个环境中不存在。
    【解决方案3】:
    <html>
    <body>
    <form target='userCountFrame' action='http://www.google.com'></form>
    <iframe name='userCountFrame'></iframe>
    <script>
    setInterval(function(){
      document.getElementsByTagName('form')[0].submit();
    }, 10 * 60 * 1000);
    </script>
    </body>
    </html>
    

    相应地更改url,将上面的代码保存为count.html到你的桌面,然后用火狐打开

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 2012-12-10
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2014-06-13
      • 2012-07-19
      相关资源
      最近更新 更多