【进阶版】修改input表单时自动更新到数据库,无需提交,当input内容改变时自动提交到MySQL

2023-08-20 建站知识 浏览 手机预览
文章来源:http://www.imtr.cn/html/n267.html

首先引入jquery文件并给表单设置相关css:

<script src="./jquery.js"></script>
<style>
    .inw{width:100%;text-align:center;border-style:none;height:35px;}
    .xtjh{color:#939393;cursor:pointer;}
    .xtok{color:#009688;font-weight:800;}
</style>


接着给input增加 data-id 属性,如下:

<input type='text' data-id='12' value='' autocomplete='off' class='inw xtjh' readonly >

autocomplete='off'  关闭表单的自动填写

readonly    表单设置为只读,禁止修改(但是可以提交)


用js代码实现双击移除readonly属性,鼠标离开时添加readonly属性

<script>
//双击执行操作
$("input[data-id]").on("dblclick", function() {
    $(this).prop("readonly", false); // 移除 readonly 属性
$(this).removeClass("xtjh").addClass("xtok"); // 修改类名
    var val = $(this).val();// 设置输入框焦点到文本末尾
    $(this).val("").focus().val(val);
});
//光标离开时操作
$("input[data-id]").on("focusout", function() {
    $(this).prop("readonly", true);// 添加 readonly 属性
    $(this).removeClass("xtok").addClass("xtjh");// 修改类名
});
//input内容改变时触发
$("input[data-id]").on("input", function() {
    const inputvalue = $(this).val();
    const inputid = $(this).data("id"); // 获取 data-id 属性的值
    $.ajax({// 发起 AJAX 请求
        type: "POST", // 或 "GET",根据需要选择
        url: "index.php", // 指向处理请求的 PHP 文件
        data: { id: inputid, value: inputvalue }, // 发送到服务器的数据
success: function(response) {
                 //alert("修改成功");
            }
    });
});
</script>


index.php代码:

<?php
//如果页面是以POST方式打开才能执行写入数据库
if($_SERVER['REQUEST_METHOD'] == "POST"){
    $inputid = $_POST['id'];
    $inputvalue = $_POST['value'];
    $sql = "update imtr_admin set bz = '$inputvalue' where id = '$inputid'";
    mysqli_query($con, $sql);
exit();
}
?>



原文地址:http://www.imtr.cn/html/n267.html
  • 如果你的问题还没有解决,可以点击页面右侧的“ ”,站长收到问题后会尽快回复解决方案到你的邮箱。
  • 创造始于问题,有了问题才会思考,有了思考,才有解决问题的方法,才有找到独立思路的可能。 —— 陶行知