PHP生成JSON数组后前端遍历仅返回最后一个pcode值问题咨询
问题原因
- 你在循环体内每次都对
msg变量进行覆盖赋值,同时每次循环都直接替换#PopupBody的DOM内容,前面的pcode渲染结果会被后续循环的内容直接覆盖,自然只能看到最后一次循环的30005 - 逻辑顺序错误:你把状态判断、DOM渲染、弹窗弹出的逻辑都写在了循环体内部,状态判断完全没必要每次循环都执行,弹窗也会被重复触发多次
修复后的代码
success: function(response) { // 先做全局状态判断,不需要放在循环里 if (response.status !== 0) { const msg = 'ERROR (' + (response.error || '未知错误') + ')'; $("#PopupBody").html(msg); $("#ModalPopup").modal('show'); return; } // 提前初始化msg变量,循环内做拼接而不是覆盖 let msg = ''; for (let i = 0; i < response.rpcresult.length; i++) { msg += '<h2>' + response.rpcresult[i].pcode + '</h2>'; } // 循环结束后统一渲染DOM、弹出弹窗 $("#PopupBody").html(msg); $("#ModalPopup").modal('show'); }
可选优化方案
如果习惯用数组方法,也可以用map直接生成所有pcode的DOM字符串,代码更简洁:
success: function(response) { if (response.status !== 0) { const msg = 'ERROR (' + (response.error || '未知错误') + ')'; $("#PopupBody").html(msg); $("#ModalPopup").modal('show'); return; } const msg = response.rpcresult.map(item => `<h2>${item.pcode}</h2>`).join(''); $("#PopupBody").html(msg); $("#ModalPopup").modal('show'); }
内容的提问来源于stack exchange,提问作者mastro
相关产品推荐
相关产品推荐

