javascript - Ajax 更新 textarea 没有按钮或页面刷新
问题描述
我正在尝试创建一个无需按下按钮或刷新页面即可自动更新数据库的文本区域。在“keyup”发生后,会有一个倒计时 2 秒的计时器。如果在这 2 秒内没有进行其他输入,则应在数据库中更新数据。如果进行了输入,则计时器将重新启动。
我已经写了下面的ajax代码,它似乎不起作用。
$(document).ready(function() {
var timer;
$('#about').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#about").submit()
alert(value);
}, 2000);
});
var about = $('#about').val().trim();
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: about
},
success: function(response) {
$('#cid').val(response);
}
});
});
/* This is comment.php */
<?php
session_start();
require_once 'config/config.php';
require_once 'includes/auth_validate.php';
$cid = $_GET['customer_id'];
$about = $_POST['about'];
$sql = ("UPDATE patient_id SET about = ? WHERE id = ?;");
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "si", $about, $cid);
mysqli_stmt_execute($stmt);
?>
解决方案
将 ajax 移动到超时,而不是执行提交,因为您想使用 ajax 进行更新。
$(document).ready(function() {
var timer;
$('#about').on('input', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
alert(value);
$.ajax({
url: "comment.php?customer_id=" + "<?php echo $customer_id; ?>",
type: 'post',
data: {
about: value
},
success: function(response) {
$('#cid').val(response);
}
});
}, 2000);
});
});
推荐阅读
- c++ - 如何正确使用 std::getline
- javascript - 带有 Vue CLI 的 Vue 2 - 如何使 src/static 静态以便我可以使用其中的图像?
- c# - C# 条件运算符
- python - 使用 python 或命令行组合 csv 文件会在输出文件中产生错误
- google-apps-script - 谷歌表格下拉“输入必须在指定范围内”。如何解决这个问题?
- flutter - Flutter web-禁用空格键滚动?
- azure - Azure 函数:限制并发服务总线消息的数量
- python - 想为我的案例实现“to_datetime”功能
- javascript - 减慢周期(for of)?
- python - 在python中计算子目录