javascript - 刷新 div ajax 中的元素

标签 javascript php jquery html ajax

我有一个小型网络应用程序,用于管理一些类(class)并报告它们的统计信息(已完成和未完成)。当点击.finish按钮时,我想刷新类(class)的统计div

这是 php 文件:

 <?php
    include_once('config_mysql.php');
    $data = new MysqlClass();
    $data->connect();
    $sql = "select * from Lessons";
    $result = mysql_query($sql);
    <div class="history">
    while($row = mysql_fetch_array($result)) {
     <div>
      <h2>name: <?php echo $row['name']; ?>
      <h2>completed: <?php echo $row['completed']; ?>
     </div>
    }
   </div>
    ?>

以及附加到 .finish 类的事件处理程序:

$(document).ready(function () {
    $('.finish').click(function(event){
        completeLesson();
         $.ajax({
                    type: "POST",
                    url: "statistic.php",
                    success: function(html){

                    }
        });  
    }
}

我没有包含 completeLesson() 函数(它也会进行 AJAX 调用),因为它并不重要。

我想刷新类(class)统计而不刷新页面。我尝试使用 AJAX 调用刷新它,但它没有更新数据。预先感谢您的回答。

最佳答案

您至少有 2 个问题。

首先,您需要对变量 html 执行一些操作在你的success回调。

第二,自 completeLesson进行自己的 ajax 调用,您必须等待该调用返回,然后才能调用 statistic.php。如果您不等待,第二个 Ajax 调用有可能会在第一个 Ajax 调用之前完成,并且不会引入新数据。

一种解决方案是传递 completeLesson第二个 Ajax 调用作为回调函数。

function completeLesson ( /* your other arguments */, callback) {
    // this would be the Ajax call already in completeLesson
    $.ajax ( {
        // whatever arguments you use for the ajax call
        success: function (data) {
            // the code you had in here before...
            // after all that code add these 2 lines
            if (callback)
                callback();
        }
    });
}

现在,您将 finish 的事件监听器更改为(假设 statistic.php 在 <div id="result"><?php include 'statistic.php'; ?></div> 之间回显,并且您已将 id="#hs" 添加到 .history div):

$('.finish').click(function(event) {
    completeLesson(function() {
        $.ajax({
            type: "POST",
            url: "statistic.php",
            success: function(html) {
                $('#hs').remove();
                $('#result').prepend(html);
            }
        });
    });  
}

您可能想使用 $('#result').append(html) 而不是 prepend .

关于javascript - 刷新 div ajax 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521883/

相关文章:

javascript - 如何从 JSON 响应动态填充 div

javascript - 更改 dojo dijit 的文本

php - 从 php 和 mysql 构建 json 的最有效方法

javascript - django 模板仅在 jquery 对话框中显示内容

jquery - 删除某个按钮后 div 内没有元素的文本

javascript - Rails 4 不执行 $(document).ready(ready);功能

javascript - 千分之一 (‰) 符号导致 div innerHTML 自动换行 (Javascript/HTML)

php - for循环中随机序列的html表

php - 使用嵌套字段进行多索引搜索

javascript - onswitchchange 后禁用 Bootstrap 开关