我正在创建一个文本框,其中文本将在用户键入后自动更新为 mysql,无需提交。现在的问题是文本框不会更新数据库。这是我通过参考下面的所有意见编辑的内容,但仍然存在一些问题,但现在显示总比没有好。谢谢。
这是文本框输入
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onKeyPress='"getComment($id,this)'" /></td>";
这是我的 JavaScript
function getComment(id, txt_box)
{
var value = txt_box.value;
$.ajax({
'url': 'updatecomment.php',
'data': {"id": id, "comment": value},
'success': function (response) {
console.log(response);
//TODO: use server response
}
});
}
最后是更新评论.php
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$id =$_GET['id'];
$comment = $_GET['comment'];
$query = "UPDATE tblinternapplication SET comment = '".mysql_real_escape_string($comment) ."' WHERE id = $id";
$result = mysql_query($query, $connection);
?>
以下是您的代码
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onPressKey='"getComment($id,this.id)'" required/></td>";
将其更改为
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onKeyup='"getComment('$id',this.value)'" required/></td>";
基本上,当您为 javascript 函数传递值时,如果您传递的值是字符串或整数而不是变量,请将它们括在单引号中,例如 getComment('$id',this.value(
我添加的另一个更改是onKeyup而不是onKeyPress。这是因为当按下某个键时,将发生 onKeyPress 事件,并且您调用的函数将没有您键入的最后一个字符。而onKeyPress事件将在您释放键时触发,即在键入字符后,因此您将获得在文本框中输入的所有字符
同样,在Mysql查询中始终将值括在单引号中,如下所示
$query = "UPDATE tblinternapplication SET comment = '".mysql_real_escape_string($comment) ."' WHERE id = '$id'";
希望您了解这些更改
查询有多个错误。它应该是:
$query = "UPDATE tblinternapplication SET comment = '".mysql_real_escape_string($comment) ."' WHERE id = $id";
而mysql_*
不应使用,因为它们已被弃用。 请改用MySQLi或PDO。还要注意SQL注入。
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onKeyPress='"javascript: return getComment($id,this.value);'" required/></td>";
您使用onPressKey
而不是onKeyPress
尝试替换
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onPressKey='"getComment($id,this.id)'" required/></td>";
跟
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onKeyPress='"getComment($id,this.value)'" required/></td>";
编辑:
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onKeyPress='"getComment($id,this)'" required/></td>";
在你的函数中获取值,例如
function getComment(txt_box, comment) {
var value = txt_box.value;
}
您需要再次发送文本框值而不是 id,并尝试更新您的更新查询,例如
$query = "UPDATE tblinternapplication
SET comment = ".mysql_real_escape_string($comment) ."
WHERE id = $id";
这里$id是一个整数 na dyou 最后错过了关闭 "。并尝试使用 mysqli_* 语句或 pdo 语句而不是 mysql_* 语句,因为它们已被弃用
和主要的事情是确保数据库中的注释列应该是数据类型文本,根据您的评论
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onPressKey='"getComment($id,this.id)'" required/></td>";
应该是
echo "<td class='"align-center'"><input type='"text'" name='"comment'" id='"comment'" onkeypress='"getComment($id,this.id)'" required/></td>";