php - ajax POST 到带有 SQL 的 PHP 页面
问题描述
我正在努力创建一个基于 Web 的评分应用程序。我希望我的成绩簿在用户输入数据时将分数更新到 SQL 数据库中,而不是依赖用户点击“保存”按钮。这是我第一次这样做,所以我有一些问题。
目前,此代码不会更新 SQL 表。我在这里做错了什么?
当 SQL 查询不成功时,如何添加错误处理程序?
alert()
如果 POST 失败和/或 SQL 语句未成功执行,我希望发生某种类型的事情。我将如何添加这个?有没有更安全的方法来做我想做的事情?
期望的最终结果:
用户只需在输入字段中输入分数即可更新成绩簿,无需单击保存按钮。如果发生错误导致 SQL 表无法根据用户输入进行更新,则alert
应该发生 javascript。
HTML/javascript 页面:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type='text' data-assID='6' data-usid='1' data-curScore='10' value='10'>
<script>
$("input[type=text]").change(function(){
var newScore = $(this).val();
var curScore = $(this).attr('data-curScore');
var assID = $(this).attr('data-assID');
var usid = $(this).attr('data-usid');
if (Number.isInteger(+newScore) || newScore == 'X' || newScore == 'x') {
$.ajax({
url: "SQL.php?assID=" + assID + "&usid=" + usid + "&score=" + newScore,
type: 'POST'
});
alert('Successfully scored assignment '+assID+' to '+newScore+' for user '+usid+'!');
} else {
$(this).val(curScore);
alert('The only valid input options are either an integer or \'X\'');
}
});
</script>
SQL.php页面源码:
<?php
session_start();
require '../dbh.int.php';
if (isset($_POST)) {
$usid = $_POST['usid'];
$assID = $_POST['assID'];
$score = $_POST['score'];
if (is_numeric($score)) { // If the score is an integer
if ($score == 0) {
$SQL = mysqli_prepare($connection, "UPDATE assignGrades SET status = NULL, graded=?, score=0, submitted = NULL WHERE (usid=? AND assID=?)");
mysqli_stmt_bind_param($SQL, "sss", date('Y-m-d H:i:s'), $usid, $assID);
}
else {
$SQL = mysqli_prepare($connection, "UPDATE assignGrades SET status = NULL, graded=?, score=? WHERE (usid=? AND assID=?)");
mysqli_stmt_bind_param($SQL, "ssss", date('Y-m-d H:i:s'), $score, $usid, $assID);
}
mysqli_stmt_execute($SQL); unset($SQL);
}
}
?>
解决方案
推荐阅读
- google-apps-script - 是否可以限制 Google 电子表格中的解冻行?
- html - 如何将 CSS 类标记为已弃用
- r - 如何创建具有显着差异和 2 个测量变量的多面箱线图?
- nscollectionview - NSCollectionView 作为 NSCollectionViewItem
- python - Pandas:比较行值并修改下一列的行值
- ios - 如何为我的 iOS 应用程序创建证书
- excel - 当我只有行号可以使用时,如何复制一行?
- android - 如果恢复初始生命周期状态,则需要设置 Activity
- ios - iOS/Swift - 闭包/完成块和委托/函数有什么区别?
- redirect - 如何在 Traefik v1.x 中不使用后端将多个域重定向到外部域?