首页 > 解决方案 > 插入数据后选项刷新

问题描述

列出这样的数据:

    <select class="custom-select col-md-10" id="routeList" size="8">
        <option selected>Choose...</option>
        <?php
        include( '../cnn.php' );
        $query= $db_con->query( "select routeName, id from tbroutes order by routeName" );
        $routes= $query->fetchAll();
        foreach ( $routes as $route) {
           echo "<option value=\"" . $route[ 'id' ] . "\">" . $route[ 'routeName' ] . "</option>";
       }
       ?>
   </select>

我有一个文本输入和按钮。单击按钮将新路由添加到数据库。

$('#btnSave').click(function() {
        var route = $('#textRoute').val();
        $.post("addRoute.php",{
            route: route
        }, function(addRoute){});
    });

添加路由.php

<?php
if ( $_POST ) {
    $route = $_POST[ 'route' ];
    include "../cnn.php";

    $query = $db_con->query( "insert into tbroutes (routeName) values ('$route')", PDO::FETCH_ASSOC );
} else {
    header( "location:index.php" );
}
?>

我想做的是在插入新路由后刷新选项(重新列表)而不刷新页面。

我对 Ajax 了解不多,你能帮帮我吗?

标签: phpjqueryhtmlajax

解决方案


使您的 PHP 脚本返回插入到数据库中的新 ID。

if ( $_POST ) {
    $route = $_POST[ 'route' ];
    include "../cnn.php";

    //$query = $db_con->query( "insert into tbroutes (routeName) values ('$route')", PDO::FETCH_ASSOC );
    //THIS IS AT RISK FOR SQL INJECTION, safer to use the following:

    $query = $db_con->prepare("INSERT INTO tbroutes (routeName) VALUES (?)");
    $query->execute([$route]);
    //Notice that I capitalize non-variable words in the query, this makes it easier to read

    echo json_encode(["success" => true, "uid" => $db_con->lastInsertId(), "route" => $route]); //assuming your using PDO

} else {
    echo json_encode(["success" => false]);
}

(注意,你header( "location:index.php" );不会在这里做任何事情,因为它是由 ajax 加载的。)

如果插入成功与否,我也会返回。如果插入成功,我也会返回路线,这是我个人的偏好,因为我认为使用返回数据而不是使用来自不同地方的数据更容易。

我将数据作为 JSON 字符串返回,因为这是在 Javascript 中处理数据的一种极其简单的方法。

现在,在您的 ajax 调用中捕获响应

$('#btnSave').click(function() {
    var route = $('#textRoute').val();
    $.post("addRoute.php",{
        route: route
    }, function(addRoute){
        addRoute = JSON.parse(addRoute); //this may or may not be necessary, depending on your environment
        if(addRoute.success) {
            $('#routeList').append(
                $('<option>', {value: addRoute.uid, text: addRoute.route})
            );
        } else {
            //failed to insert
        }
    });
});

推荐阅读