【发布时间】:2019-10-13 10:18:54
【问题描述】:
我在单击按钮时通过 JavaScript 发送 ajax 请求。单击按钮时,会从执行 ajax 请求的位置调用函数。
这是调用函数的html代码:
echo "
<form > ";
if ($status == 'regular') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='official' name='status'>";
echo "<td><button class='btn btn-info' onclick='UpdateStatus(".$id.",'official')'>UPDATE TO OFFICIAL</button><br><br>";
}
if ($status == 'official') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='regular' name='status'>";
echo "<td><button class='btn btn-success' onclick='UpdateStatus(".$id.",'regular')'>UPDATE TO REGULAR</button><br><br>";
}
echo "</form>";
UpdateStatus()是有ajax请求的函数。我从这里发送$id,这是用户 ID 和要更新的状态。
这里是 UpdateStatus() 函数:
<script>
function UpdateStatus(str,str1) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//ready
};
xmlhttp.open("GET", "update_status.php?id=" + str + "&status=" + str1, true);
xmlhttp.send();
}
}
</script>
str 和 str1 分别是 ID 和状态。这是update_status.php:
<?php
$id = $_REQUEST["id"];
$status = $_REQUEST["status"];
$server_name = "localhost";
$user_name = "root";
$password = "";
$db = "diwan";
$conect = new mysqli($server_name, $user_name, $password, $db);
if($conect->connect_error)
{ die("Connection failed ".$conect->connect_error); }
$sql = "UPDATE user SET status = '$status' WHERE UserID = $id";
if(!$conect->query($sql))
{echo "error in adding record ".$conect->error;}
$result = $conect->query($sql);
?>
当我点击按钮时,我会得到这种格式的网址:
http://localhost/diwan_web/manageusers.php?id=2&status=official
但它不会更新数据库中的数据。请指导我哪里错了或者有什么遗漏。任何建议都将受到高度赞赏。
【问题讨论】:
-
“txtHint”的目的是什么?当您单击更新按钮时,您是否获得函数 UpdateStatus(str,str1) 中的值?您可以使用 console.log(str,str1);内部函数。
-
是的,这些值正在进入函数并进入下一页,我也发布了网址,您可以查看
-
在代码中使用
die(mysqli_error($conn));是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die? -
这只是一个测试一些东西的示例代码,我会在项目中避免这些东西
-
您正在运行更新查询两次。一次在
if中,然后再次将返回值分配给$result。
标签: javascript php html mysql ajax