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

多实例jQuery通过Ajax向PHP传递数据异常问题求助

嘿,我来帮你搞定这个问题!你遇到的核心问题是JavaScript循环里的闭包陷阱,还有几个语法小错误,咱们一步步来修正:

问题根源分析

  1. 循环变量的作用域问题:你用for循环绑定事件时,var声明的i是函数作用域,所有事件触发时i的值都会变成循环结束后的6,根本找不到对应ID的元素。
  2. 非法变量命名:var data+i = ...这种写法不符合JavaScript语法,不能用加号来命名变量。
  3. ID匹配错误:你的HTML隐藏输入框ID是building_id_xxx,但jQuery里写的是$('#building_'+i),两者不匹配,导致拿不到正确的建筑ID。
  4. 多余的eval:你已经指定了dataType:'JSON',jQuery会自动把响应解析成JSON对象,完全不需要用eval(data)。

修正方案(推荐简洁版)

咱们直接简化HTML结构,把建筑ID存到checkbox的value属性里,再用类选择器统一绑定事件,彻底避开闭包问题。

修正后的HTML

<input type="checkbox" class="toggle" name="toggle" data-toggle="toggle" data-off="Disabled" data-on="Enabled" value="<?php echo $row["id"];?>">

修正后的jQuery代码

$(document).ready(function(){
  // 给所有带toggle类的checkbox绑定change事件
  $('.toggle').change(function(){
    // 获取当前开关的状态
    var mode = $(this).prop('checked');
    // 直接从当前checkbox的value拿到对应建筑ID
    var building_id = $(this).val();
    
    $.ajax({
      type: 'POST',
      dataType: 'JSON',
      url: 'admin/sites/audio_alarm.php',
      data: { mode: mode, building_id: building_id },
      success: function(response) {
        // 这里把参数名改成response,避免和内部变量冲突
        $("#heading").html(response.success);
        $("#body").html(response.message);
      },
      // 加上错误处理,方便调试
      error: function(xhr, status, error) {
        console.log('AJAX请求出错:', error);
        $("#heading").html('错误');
        $("#body").html('更新状态失败,请稍后重试');
      }
    });
  });
});

如果你想保留原HTML结构(checkbox+隐藏输入框)

可以给checkbox加统一的类,然后通过相邻元素选择器找到对应的隐藏输入框:

对应HTML

<input type="checkbox" class="toggle" name="toggle" id="toggle<?php echo $row["id"];?>" data-toggle="toggle" data-off="Disabled" data-on="Enabled">
<input type="hidden" name="building_id_<?php echo $row["id"];?>" id="building_id_<?php echo $row["id"];?>" value="<?php echo $row["id"];?>">

对应jQuery代码

$(document).ready(function(){
  $('.toggle').change(function(){
    var mode = $(this).prop('checked');
    // 找到当前checkbox后面的隐藏输入框,获取建筑ID
    var building_id = $(this).next('input[type="hidden"]').val();
    
    $.ajax({
      type: 'POST',
      dataType: 'JSON',
      url: 'admin/sites/audio_alarm.php',
      data: { mode: mode, building_id: building_id },
      success: function(response) {
        $("#heading").html(response.success);
        $("#body").html(response.message);
      },
      error: function(xhr, status, error) {
        console.log('AJAX请求出错:', error);
        $("#heading").html('错误');
        $("#body").html('更新状态失败,请稍后重试');
      }
    });
  });
});

核心思路总结

不要再用循环逐个绑定事件啦!通过类选择器统一绑定事件,然后用$(this)获取当前触发事件的元素,这样每个开关触发时都能拿到对应的状态和建筑ID,完美解决多实例的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:30:29