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

如何在jQuery中遍历Ajax返回的数组并获取原料ID、名称与数量?

解决原料ID与数量的获取问题

问题根源

你当前的PHP代码是循环输出单个JSON数组,导致响应内容是多个独立JSON的拼接(比如[54,"Vanilla Cake Mix",2000] [126,"Water",1200]),这不是合法的JSON格式,所以jQuery无法自动解析为数组,each循环自然失效。

第一步:修正PHP代码

把所有原料数据放到一个外层数组中,再统一输出JSON:

// 初始化一个空的外层数组
$materials = [];
// 假设你是从数据库循环获取原料数据,比如:
while ($row = /* 你的数据库查询结果(如mysqli_fetch_assoc) */) {
    $raw_material_id = $row['id'];
    $raw_material_name = $row['name'];
    $raw_material_quantity = $row['quantity'];
    // 将单条原料数据加入外层数组
    $materials[] = [$raw_material_id, $raw_material_name, $raw_material_quantity];
}
// 输出整个数组的JSON格式
echo json_encode($materials);

修正后输出的响应是合法的JSON数组:

[[54,"Vanilla Cake Mix",2000],[126,"Water",1200],[1,"Refined Soyabean Oil",200]]

第二步:修正jQuery代码

现在响应是合法JSON,dataType: "json"可以正常解析,直接用$.each遍历每个原料项:

$.ajax({
    type:"POST",
    url:"api_consumption.php",
    data: "product_recipe_id="+product_recipe_id+"&quantity="+value,
    dataType: "json",
    success: function(materials) {
        // 遍历每个原料数组
        $.each(materials, function(index, item) {
            var rawMaterialId = item[0];   // 原料ID
            var rawMaterialName = item[1]; // 原料名称
            var rawMaterialQty = item[2];  // 原料数量
            // 这里可以执行你需要的操作,比如打印或渲染到页面
            console.log("原料ID:" + rawMaterialId + ",数量:" + rawMaterialQty);
        });
    }
});

额外提示

  • 推荐用data: {product_recipe_id: product_recipe_id, quantity: value}的格式传递数据,比字符串拼接更规范且不易出错。
  • 若暂时无法修改PHP,也可在前端手动修复响应格式(比如把空格替换为逗号,再在外层包裹[]),但这种方法属于临时 workaround,不建议长期使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:55:18