php - 插入数据后选项刷新
问题描述
列出这样的数据:
<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 了解不多,你能帮帮我吗?
解决方案
使您的 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
}
});
});
推荐阅读
- r - 尝试使用 ggplot2 将图例添加到线图中,但没有出现
- c# - 在.net核心项目中发布时获取资产文件没有targetframework异常
- powershell - 使用 PowerShell 创建日志文件摘录
- vb.net - vb.net:带有打开对话框的应用程序在任务栏中显示两次
- security - 在 Quarkus 中记录身份验证失败
- javascript - 如何将数组从 XMLHTTPREQUEST API POST 保存到 Laravel 控制器
- javascript - 如何将数据从 C# 文本框发送到 HTML 文本框?
- swift - 在范围列表中查找子范围
- python - Scrapy MySQL 管道
- linux - DPDK 应用程序测试管道在 app_ports_check_link 中失败