【问题标题】:how to refresh php div every few seconds如何每隔几秒钟刷新一次php div
【发布时间】:2016-12-30 06:39:37
【问题描述】:

所以我基本上是在尝试用 php 和(可能是最小的)javascript 实现一个在线交易纸牌游戏,到目前为止,我在 php 中设置了一个 GUI,一个包含所需表的数据库(到目前为止)来保存甲板,字段和其他各种数据。我已经做到了,我有一个函数可以初始化两个玩家的字段,并用他们的牌组中的牌填充他们的字段和手。我还做到了,另一台计算机或设备上的玩家可以获取游戏的房间号并加入游戏,以便查看确切的初始化字段。

我的下一个目标是能够设置回合逻辑,并允许一个玩家更新屏幕,而另一个玩家在他们的回合中进行游戏。我的问题是我不确定最小可行的解决方案是什么,因为我有很长的复杂函数,这些函数根据来自字段表的值显示当前字段。所以我的理想逻辑是这样设置的:

//find game form

//host game form

//if host is set (post){
  //call insert field function (a long function that creates a table for the current game being played and initializes the field and hand with random cards from the deck table)  
  //link game to host for future field printing
  // populate host function (a function that prints a table of every card on the field with the most up to date variables to represent each spot) 
}

//if find is set (post){
  //call insert field function
  //link game to host for future field printing
  //a button form to start the game which begins by calling heads or tails
  // populate find function (same as host but for find player side)
}

//if start game is set (post){
  // do game logic such as coin flip which will be notified to opponent in a message field in the game table upon the refresh
}

我将填充主机功能包装在一个可刷新的 div 中,如下所示:

print "<div><meta http-equiv='refresh' content='5' />"; //host populate just disapears
populatehost($roomnumber); //populates self and opponents in hosts perspsective
print "</div>";

这样该函数将每 5 秒左右调用一次,但这只会导致该字段在 5 秒后消失。所以...

  1. 为什么会消失?

  2. 如何让它刷新页面并使用填充字段功能只显示一个字段实例?

  3. 这种方法可行吗?如果没有,我可以采取的最简单的方法是什么?如何做?

  4. 我还尝试了一个解决方案,该函数每 5 秒调用一次并摆脱,但我不确定我是否做得对,PHP 手册没有解释得很清楚,经过大量试验和错误我认为我的服务器崩溃了。是这样的:

    //循环

    ob_start();
    populatehost($_SESSION['gamenumber']);
    sleep(5);
    ob_end_clean();
    

我一直在玩这个逻辑,但它要么无限打印,要么根本不打印,要么让我的服务器崩溃。我害怕玩得更多,因为害怕再次崩溃服务器。也许有人可以解释正确的方法,或者如果不可行,为什么不可行?

很抱歉,如果这些都是愚蠢的问题,我已经花了几天时间研究解决这个问题的方法,我不确定是否可以使用 javascript 或 ajax 以及我的现场打印功能来实现它,我尝试了一些他们没有工作,我不确定是不是因为我的方法是可行的。

【问题讨论】:

    标签: javascript php jquery ajax page-refresh


    【解决方案1】:

    您可以为 div 获取 javascript 或 Ajax 帮助,您可以为 div 分配 id 并在 javascript 中调用 id:

    jQuery(function () {
        var $els = $('div[id^=quote]'),
            i = 0,
            len = $els.length;
    
        $els.slice(1).hide();
        setInterval(function () {
            $els.eq(i).fadeOut(function () {
                i = (i + 1) % len
                $els.eq(i).fadeIn();
            })
        }, 2500)
    })
    

    检查这个小提琴:

    http://jsfiddle.net/arunpjohny/asTBL/

    谢谢

    【讨论】:

    • 对不起,我对 jquery 不太熟悉。我必须在我的 php 文件中在哪里打印这个函数才能工作?有什么我必须在我的文件顶部导入才能让 jquery 工作吗?
    • 你需要启动脚本标签 你需要在哪个文件中添加这个代码你的 div 你想要刷新的那个然后需要调用普通js文件
    • 另外,您需要将您的 div id 传递到上面的脚本中,而不是引用
    • 我应该把我的脚本标签放在哪里?上面的div?在div之后?在页面顶部?
    • 这很奇怪。我把脚本放在文件末尾,就在
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签