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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:51:00