javascript - 尝试在插入之前检查 sql 表值是否已经存在
问题描述
我有一个带有 id 列和位置名称列的基本表。我还有一个 html 表单,用户可以在其中将新位置插入表中。在插入之前,我想检查我的位置表是否已经包含位置名称,如果它确实存在,我想提醒用户。如果不是,它将被插入到表中。首先我查询位置表,然后尝试使用 if 语句来查看输入值是否已经与我的表中的位置名称匹配。但我无法让它工作。我的插入代码本身可以正常工作,但我无法使条件正常工作。任何帮助将不胜感激。
// add a new location
$("#btn-locationAdd").on("click", function() {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
alert('This location aready exists')
} else {
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
这是我在查询位置表并获取表中的所有位置后得到的数组:
{
"status": {
"code": "200",
"name": "ok",
"description": "success",
"returnedIn": "1.5790462493896E-6 ms"
},
"data": [
{
"id": "1",
"name": "London"
},
{
"id": "2",
"name": "New York"
},
{
"id": "3",
"name": "Paris"
},
{
"id": "4",
"name": "Munich"
},
{
"id": "5",
"name": "Rome"
}
]
}
我的html:
<!-- Add Location Modal -->
<div id="addNewLocationModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Add New Location</h2>
</div>
<div class="modal-body">
<input type="text" class="form-control" placeholder="Location Name" id="addLocationName"><br>
</div>
<div class="modal-footer">
<input type="button" id="btn-locationAdd" value="Add Location" class="btn btn-success">
<input type="button" id="btn-addLocationCancel" value="CANCEL" data-bs-dismiss="modal" class="btn btn-secondary">
</div>
</div>
</div>
</div>
解决方案
$("#btn-locationAdd").on("click", function () {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
let existed = false;
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
existed = true
break
}
}
if(existed){
alert('This location aready exists')
return
}
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
})
})
推荐阅读
- javascript - ionic v4 angular-router,如何在视图导航之间隐藏恢复谷歌地图
- python - 如何从使用 python 解析的 yaml 文件中调用和迭代值?
- c - Linux 内核模块:printk 消息不在我期望的缓冲区日志中
- java - 多次调用的 MediatorLiveData 观察者错误
- android - 如何在混合 React-native 应用程序中传递初始属性
- regex - Nginx 删除 '?' 扩展前的符号
- html - 从 CSS 属性中排除类:not() 不起作用
- c# - 如何使用 wpf xaml 绘制均匀间隔的对角线文本
- java - 当我第二次敲击键盘输入时,我的 Do-While 循环中断
- java - 在 Windows 上安装 Java 11 OpenJDK(系统路径问题)