刷新div ajax中的元素

时间:2016-09-15 23:42:17

标签: javascript php jquery html ajax

我有一个小型Web应用程序,可以管理一些课程并报告它们的统计信息(已完成和未完成)。当我点击.finish按钮时,我想刷新课程的统计信息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),因为它并不重要。

我想在不刷新页面的情况下刷新课程统计信息。我尝试使用AJAX调用刷新它,但它没有更新数据。提前感谢您的回答。

1 个答案:

答案 0 :(得分:1)

你至少有两个问题。

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

其次,由于completeLesson进行了自己的ajax调用,因此在调用statistic.php之前必须等待该调用返回。如果你不等,第二个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();
        }
    });
}

现在,您将结束事件监听器更改为(假设statistic.php是<div id="result"><?php include 'statistic.php'; ?></div>之间的回声,并且您已将id="#hs"添加到.history 1}} 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