You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax和Jquery更新mysqli失败问题求助

解决Ajax更新数据失败的问题

我帮你排查了代码里的问题,主要有几个关键错误导致Ajax没有正常执行,咱们一步步来修复:

1. 错误获取当前记录的ID

你用var id= $('.edit').attr("id");获取ID时,会拿到页面上第一个.edit元素的ID,而不是当前点击Save按钮对应的那条记录的ID。这会导致Ajax发送错误的ID,自然无法更新正确的数据。

修复方案:

通过当前Save按钮的兄弟元素(对应的.edit按钮)获取ID,或者从Save按钮的ID里提取:

// 方案1:通过兄弟元素获取对应ID
var id = $(this).siblings('.edit').attr("id");

// 方案2:从Save按钮的ID(比如save123)里提取数字ID
var saveId = $(this).attr("id");
var id = saveId.replace('save', '');

2. BeforeSend中的动画目标错误

parent.animate({'backgroundColor':'#fb6c6c'},300);里的parent不是有效的jQuery对象,应该定位到当前记录所在的行:

beforeSend: function() {
    $('#record-' + id).animate({'backgroundColor':'#fb6c6c'},300);
}

3. 内容编辑后获取的文本不准确

你把整个<td>设为可编辑,但还是从#Q{id}里取文本,这时候编辑后的内容可能已经覆盖了原有的<span>,应该直接获取<td>的文本:

var question = $('#box'+id).text().trim(); // trim去掉多余空格

4. 请求类型与SQL注入风险

更新操作属于数据修改,用GET请求不安全且可能触发缓存;另外直接拼接变量到SQL语句里存在严重的SQL注入风险。

修复后的Ajax代码:

$.ajax({
    type: 'post', // 改成POST更安全
    url:'include/ajaxserver.php',
    data: { id: id, edit_me: true, table: table, question: question },
    beforeSend: function() {
        $('#record-' + id).animate({'backgroundColor':'#fb6c6c'},300);
    },
    success: function(data) {
        setTimeout( function ( ) {
            alert( '数据更新成功!' );
        },600 );
        // 更新页面显示的内容
        $('#Q'+id).text(question);
    },
    error: function(xhr, status, error) {
        // 添加错误调试信息
        alert('请求出错:' + error);
        console.log('服务器返回内容:', xhr.responseText);
    }
});

修复后的ajaxserver.php代码(使用预处理语句防注入):

include('connection');
if(isset($_POST["edit_me"]) && $_POST["edit_me"]=="true") {
    $id = $_POST["id"];
    $table = $_POST["table"];
    $question=$_POST["question"];
    
    // 使用预处理语句避免SQL注入
    $query = "UPDATE `{$table}` SET question=? WHERE id=?";
    $stmt = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($stmt, "si", $question, $id);
    
    if (mysqli_stmt_execute($stmt)) {
        echo "更新成功";
    } else {
        echo "更新失败:" . mysqli_error($con);
    }
    mysqli_stmt_close($stmt);
}

5. 其他细节优化

  • 点击Edit/Save时,只操作当前行的按钮,而不是所有按钮(比如原来的$('.edit').hide()会隐藏所有编辑按钮,改成$(this).hide()只隐藏当前按钮)
  • 添加错误回调函数,方便调试Ajax请求的问题
  • 打开浏览器开发者工具(F12)的Network标签,查看Ajax请求的发送状态和返回内容,这是排查Ajax问题的关键

完整修复后的JavaScript代码

$(document).ready(function() {
    //Update Question
    $('.edit').click(function(ae){
        ae.preventDefault();
        // 只隐藏当前点击的Edit按钮
        $(this).hide();
        var id = $(this).attr("id");
        $('#box'+id).addClass('editable');
        $('#box'+id).attr('contenteditable', 'true');
        $('#save'+id).show();
    });
    $('.save').click(function(){
        var $currentBtn = $(this);
        // 只隐藏当前点击的Save按钮
        $currentBtn.hide();
        var id = $currentBtn.siblings('.edit').attr("id");
        
        $('#box'+id).removeClass('editable');
        $('#box'+id).removeAttr('contenteditable');
        // 只显示当前行的Edit按钮
        $('#'+id).show();
        
        var table = $currentBtn.attr("data-table");
        var question = $('#box'+id).text().trim();
        
        alert(id+table+question);
        $.ajax({
            type: 'post',
            url:'include/ajaxserver.php',
            data: { id: id, edit_me: true, table: table, question: question },
            beforeSend: function() {
                $('#record-' + id).animate({'backgroundColor':'#fb6c6c'},300);
            },
            success: function(data) {
                setTimeout( function ( ) {
                    alert( '数据更新成功!' );
                },600 );
                $('#Q'+id).text(question);
            },
            error: function(xhr, status, error) {
                alert('请求失败:' + error);
                console.log('服务器返回:', xhr.responseText);
            }
        });
    });
});/*end of the ready function*/

内容的提问来源于stack exchange,提问作者user9168085

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:30:40