Ajax修改表格数据仅首行生效其余行无响应如何解决
问题根因
- 你使用了全局ID选择器
$("#test1")、$("#test2")获取值,HTML规范中ID是全局唯一的,因此不管触发哪一行的change事件,永远只会匹配到第一行对应ID的元素,无法获取当前行的input值 - 代码中定义的参数对象名称为
test,但AJAX请求的data字段传入的是未定义的alta变量,属于语法错误
修正后的代码
$(document).ready(function(){ $('#table').on('change', 'input', function () { // 获取当前触发事件的input所属的行 const $currentRow = $(this).closest('tr'); // 基于当前行范围查找对应input,不要用全局ID选择器 var test={ "test1": $currentRow.find(".test1").val(), "test2": $currentRow.find(".test2").val() } $.ajax({ method: "POST", url: "data.php", data: test, // 修正变量名错误 async:true, cache:false, success : function(response){ if(response=="1"){ alert("done"); } else{ alert("sad"); } }, error : function(error) { alert(error); } }); }); });
配套HTML调整要求
修改表格模板代码,把原来每行重复的id="test1"、id="test2"属性改为class="test1"、class="test2",避免ID重复冲突。如果不想用类选择器,也可以用name属性匹配:$currentRow.find('[name="test1"]').val()
内容的提问来源于stack exchange,提问作者mauroy
相关产品推荐
相关产品推荐

