0

这是我的js脚本

<script>
    function displayWarriors() {
        $.ajax({
            url: "display_warriors.php",
            success: function(data) {
                $("#tableWarrior").append(data);
            }
        });
        return false;
    }
    function createWarrior() {
        $.post( "create_warrior.php", { 
        "wname": $("#txtWname").val(),
        "wtype": $("#txtWtype").val()           
        }, 
        function(msg){
            displayWarriors();
        });
        return false;
    }
</script>

我在从我的事件中触发函数时使用这行 html 代码

<input onclick="return createWarrior()"

例如,我的桌子上显示了 No.1 Name1,然后我添加了另一个 Name 2

我的输出去了

No.1 Name1
No.1 Name1
No.2 Name2

我怎样才能解决这个问题

我的 display_warriors.php

foreach($stmt as $warrior){
        echo '<tr><td>'.$warrior['warrior_id'].'</td><td><a href="selected.php?id='.$warrior['warrior_id'].'">'.$warrior['warrior_name'].'</a></td><td>'.$warrior['warrior_type'].'</td></tr>';
    }
4

1 回答 1

3

重复即将到来,因为您总是返回所有数据,其中一些数据已经存在于“tableWarrior”元素中,您应该更改语句

success: function(data) {
       $("#tableWarrior").append(data);
}

success: function(data) {
       $("#tableWarrior").empty();
       $("#tableWarrior").append(data);
}

你应该改变

<script>
    function displayWarriors(wname, wtype) {
        $.ajax({
            url: "display_warriors.php",
            data: { name: wname, type: wtype},
            success: function(data) {
                $("#tableWarrior").append(data);
            }
        });
        return false;
    }
    function createWarrior() {
        var name =  $("#txtWname").val(),
        var type =  $("#txtWtype").val()   

        $.post( "create_warrior.php", { 
        "wname": name,
        "wtype": type           
        }, 
        function(msg){
            displayWarriors(name, type);
        });
        return false;
    }
</script>

和你的 display_warrior.php,应该返回一个战士 tr。喜欢

$name = $_REQUEST["name"];
$type = $_REQUEST["type"]
$warrior = GetYourWarriorWithItsNameAndType($name, $type);//Call a funciton here to get the warrior from its name and type.

echo '<tr><td>'.$warrior['warrior_id'].'</td><td><a href="selected.php?id='.$warrior['warrior_id'].'">'.$warrior['warrior_name'].'</a></td><td>'.$warrior['warrior_type'].'</td></tr>';
于 2012-09-11T08:04:50.693 回答