【问题标题】:Append a row to an html table with Jquery?使用 Jquery 在 html 表中追加一行?
【发布时间】:2016-12-17 19:10:47
【问题描述】:

我有一个简单的表单,可以将数据插入 mysql 数据库并显示数据库中的数据,包括刚刚使用 ajax 在表中发布的数据。 目前,整个表格在提交表单后会刷新,但我想弄清楚如何将一行附加到显示刚刚提交的数据的表格结果中。谁能解释我如何实现这一目标?

表格

<div class="form-group">
    <form class="" action="" id="post_data" method="post">
        <label>
                Post Data
              </label>
        <input id="input" name="input" type="text" class="form-control input-md">
</div>
<button type="submit" class="btn pull-right btn-primary" id="submit">
              Save
            </button>
</form>

<div class="display" id="display"></div>
</div>

<script>
    $(document).ready(function() {
        $('#post_data').submit(function() {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                dataType: 'html',
                data: $(this).serialize(),
                success: function(newContent) {
                    $('#display').html(newContent);
                }
            });

            return false;
        });
    });
</script>

进程.php

$stmt = $db_conx->prepare('INSERT INTO ajax_test (input) VALUES (?)');
$stmt->bind_param('s', $input);
$stmt->execute();
$sql = "SELECT input FROM ajax_test";
$result = mysqli_query($mysqli, $sql);


while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $id . "</td>";
    echo "<td>" . $row["input"] . "</td>";
    echo "</tr>";
}
}
mysqli_close($mysqli);

【问题讨论】:

  • 我在您的 HTML 中没有看到表格,但如果您的意思是 #display,请使用 append() 而不是 html()
  • 另外,您的 html 无效。您的 form 元素正在关闭 您的 &lt;div&gt;

标签: php jquery ajax loops append


【解决方案1】:

使用 append() 代替 html();

$('#display').append(newContent);

或者如果您想在表格顶部添加新内容

$('#display').prepend(newContent);

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 1970-01-01
    • 2013-03-29
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多