簡體   English   中英

刷新div ajax中的元素

[英]Refresh element in a div 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調用刷新它,但是它沒有更新數據。 預先感謝您的回答。

您至少有2個問題。

首先,您需要在success回調中使用變量html進行操作。

其次,由於completeLesson進行了自己的ajax調用,因此您必須等待該調用返回,然后才能調用statistic.php。 如果您不等待,那么第二個Ajax調用可能會在第一次調用之前完成,並且不會引入新數據。

一種解決方案是將第二個Ajax調用傳遞給completeLesson作為回調函數。

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 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM