簡體   English   中英

AJAX加載頁面並在成功后重新加載/添加

[英]AJAX load page and reload/add after success

因此,我有一個頁面,該頁面可應要求更新我的數據庫。 例如,當我轉到database_update.php它只會更新數據庫,而不會顯示任何內容。

Index.php顯示用戶數據庫內容。

因此,我在JavaScript中具有稱為update函數,該函數必須使用AJAX來運行此頁面,並且在頁面加載后(所有查詢成功運行之后),它必須加載index.php並向用戶顯示更新的頁面(重新加載頁面,而不會產生刷新效果)。

我的代碼是這樣的:

$.get('ajax_update_table.php', {
    // The following is important because page saves to another table
    // users nick which call update:
    update: UserLogin
}, function (output) {
    // The following is unimportant:
    $(myDiv).html(output).show();
});

兩個建議:

  1. 從您的database_update腳本返回“成功”或“錯誤”代碼。 返回JSON字符串非常簡單。 例如:

     echo '{"success":"success"}'; 
  2. 使用$ .ajax函數。 然后添加成功,錯誤和完整參數。 AJAX請求完成后,您可以調用任何javascript函數。

     $.ajax({ url: 'update_database.php', dataType: 'json', success: function (data) {successFunction(data)}, error: function () { error(); }, complete: function () { complete(); } }); function successFunction(data) { if ('success' in data) { // Do success stuff here. } else { // Show errors here } } // .... etc 

我可能會丟失一些東西,但我會盡力回答您的問題。

我會設置一個空白頁,在加載時將其發送index.php到該頁上的div。 例如,制作一個標題為blank.php的頁面。

blank.php將具有以下內容:

function Index(){
$.ajax({
    url:"index.php",
    type: "GET",
    success:function(result){
        $("#web-content").html(result);
    }
});
}

<script type="text/javascript">Index();</script>
<div id="web-content"></div>

然后,您可以讓索引執行Index函數,以使用index.php數據更新Web內容div,而無需重新加載blank.php頁面。

得到它的工作!

我的index.php

<html>
<head>
    <script type="text/javascript" language="Javascript" SRC="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" language="Javascript">
    function update_and_replace()
        {
            $.ajax({
                url: 'ajax_update_table.php',
                dataType: 'json',
                success: function (data) {successFunction(data)},
                error: function () { error(); },
                complete: function () { complete(); }
            });
        }

        function successFunction(data) {
            if ('success' in data) {
                $("#content").load("index.php");
            } 
        }

    </script>
</head>
<body>
<div id='content'>
Now is: <?php echo date("Y-m-d, H:i:s");?>
<br/><br/><br/><br/>
<a href="javascript:void(0);" onClick="update_and_replace();">Aktualizuj</a>
</div>
</body>
</html>

Ajax_update_table.php

<?php echo '{"success":"success"}'; ?>

謝謝大家的幫助。 我知道我的英語不好,但是在你的幫助下我做到了!

暫無
暫無

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

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