【问题标题】:AJAX Div Refresh with PHP使用 PHP 刷新 AJAX div
【发布时间】:2017-02-07 20:16:19
【问题描述】:

我正在尝试不时刷新页面上的一些元素。我知道这里有一百万个关于这个的话题,我试图让我的工作,但这是我需要更新的内容..

这是页面加载时生成的代码:

<div id="galleria">

    <?php
    $a = array();
    $dir = '../public/wp-content/uploads/2012/01';
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
        if (preg_match("/\.png$/", $file)) $a[] = $file;
        elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
        elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
      }
      closedir($handle);
    }

    $totalImgs = count($a);
    $imgUsed = array();
    for ($j = 0; $j < 100; $j++)
    {
        do
        {
            $randIndex = mt_rand(0, $totalImgs);
        }
        while ($imgUsed[$randIndex] === TRUE);
        $imgUsed[$randIndex] = TRUE;
        echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
    }

    ?>  

</div>

我想每 10 秒自动刷新一次,但不重新加载页面。我已经阅读了 ajax,似乎这是可能的,但我似乎无法让它工作。

所做的只是显示 Galleria div,并在 div 中加载 100 张图像。然后 Galleria 脚本接管并很好地显示它。 AJAX 或 JQuery 会更好吗?

感谢您的帮助!

【问题讨论】:

    标签: ajax jquery partial-page-refresh


    【解决方案1】:

    “AJAX 和 jQuery 会更好吗?” -- AJAX 是一种技术,jQuery 是一个库。事实证明,jQuery 为 AJAX 提供了出色的 API。

    我们将这段 PHP 称为“galleria.php”。在原始页面加载时,它使用良好的 ol'&lt;?php include('galleria.php')?&gt; 插入到父 PHP 页面中。现在最终用户看到的是完整的初始化页面。

    要更新它,您有许多可用的 AJAX 选项,但最简单的方法是在您的页面中包含 jQuery,然后您可以在脚本中使用 .load()

    var updateGallery = setInterval(function() {
      $('#someDiv').load('galleria.php');
    }, 10000);
    

    还有调整的余地...也许galleria.php 不包括页面上设置的&lt;div id="galleria"&gt;。在这种情况下,您将直接加载到 #galleria 而不是 #someDiv 并为自己节省一个不必要的容器。也许您通过在不同的范围内声明 $('#someDiv') 对象来缓存它,以便可以重用它。但这是一般要点。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 所以指向外部资源的链接算作一个更好的答案,因为他能够在不到一分钟的时间内快速发出它(因为我正在写一些有实质内容的东西)?答案应该是独立的。甚至没有赞成票?有时我想放弃 Stack Overflow。 :-D
      【解决方案3】:

      正如我写的here,您可以使用 jQuery ajax 调用填充 div。

       <html>
          <head>
          <script type="text/javascript">
              function refresh_gallery(){
                  $.ajax({
                      type: "POST",
                          url: "generate_gallery.php",  // your PHP generating ONLY the inner DIV code
                          data:   "showimages=100",
                          success: function(html){
                              $("#output").html(html);
                          }
              });  
          }
      
          $(function() {
          refresh_gallery(); //first initialize
      
          setTimeout(refresh_gallery(),10000); // refresh every 10 secs
      
              });
      
          </script>
      </head>
      <body>
          <div id="output"></div>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-08
        • 2014-04-23
        • 1970-01-01
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        相关资源
        最近更新 更多