使用执行外部连接的 PHP 脚本中的 jQuery 更新页面信息

Updating page info using jQuery from a PHP script that performs an external connection

我有一个 PHP 脚本,它使用 file_get_contents 执行到我的其他服务器的连接,然后检索并显示数据。

    //authorize connection to the ext. server
    $xml_data=file_get_contents("http://server.com/connectioncounts"); 
    $doc = new DOMDocument(); 
    $doc->loadXML($xml_data);

    //variables to check for name / connection count
    $wmsast = $doc->getElementsByTagName('Name'); 
    $wmsasct = $wmsast->length; 

    //start the loop that fetches and displays each name
    for ($sidx = 0; $sidx < $wmsasct; $sidx++)  { 
    $strname = $wmsast->item($sidx)->getElementsByTagName("WhoIs")->item(0)->nodeValue; 
    $strctot = $wmsast->item($sidx)->getElementsByTagName("Sessions")->item(0)->nodeValue;  

    /**************************************
    Display only one instance of their name.
    strpos will check to see if the string contains a _ character
    **************************************/
    if (strpos($strname, '_') !== FALSE){
        //null. ignoring any duplicates
    }
    else {
        //Leftovers. This section contains the names that are only the BASE (no _jibberish, etc)
        echo $sidx . " <b>Name: </b>" . $strname . " Sessions: " . $strctot . "<br />";

    }//end display base check

}//end name loop

在客户端,我使用 jQuery load () 调用此脚本并使用 mousemove() 执行。

$(document).mousemove(function(event){
    $('.xmlData').load('./connectioncounts.php').fadeIn(1000);
});

而且我还尝试了 set interval 效果一样好:

var auto_refresh = setInterval(
    function ()
    {
        $('.xmlData').load('./connectioncounts.php').fadeIn("slow");
    }, 1000); //refresh, 1000 milli = 1 second

一切正常,内容出现在 "real time" 中,但我已经注意到对性能的影响,而且只有我在使用它。

我正在努力想出一个更好的解决方案,但达不到要求。我现在遇到的问题是每个客户端都会强制脚本启动与另一台服务器的新连接,因此我需要一个解决方案来持续更新信息而不涉及客户端直接建立新连接。

我的一个想法是使用执行脚本的 cron 作业,并修改 PHP 以记录内容。然后我可以简单地从客户端获取该缓存的内容。这意味着每次客户端需要数据时,只会建立一个连接,而不是强制建立一个新连接。

唯一的问题是 cron 必须 运行 频繁,比如每隔几秒。我以前读过很多人 运行ning cron,但我遇到的每个实例都不是每次都建立外部连接。

除了 cron 之外,我还有其他选择可以实现此目的吗?或者根据您的经验,这是否足够好?

让自己熟悉 APC 作为全局存储。获取文件后,将其存储在 APC 缓存中并设置超时。一旦页面不在缓存中或已过时,您只需要连接到远程服务器。

Mousemove:你确定吗?这会生成大量并行请求,除非您将信号量客户端设置为不再发出任何 AJAX 查询。

这个怎么样: 当第一个客户端读取您的数据时,您从远程服务器检索它们并将它们与时间戳一起缓存。

当下一个客户端读取相同的数据时,您检查缓存内容的时间,只有当它超过 2 秒(或其他)时,您才再次访问远程服务器。