读取ajax中的对象数组数组

时间:2017-03-14 17:16:24

标签: javascript php json ajax

我有一个来自ajax调用的三个数据。我将它们打包成这样的数组:

return json_encode([$salesOrder, $soAddressDetails, $lineItems]);

然后我转到视图并查看返回。我看到(例如)这个:

[
    [{
        "id": 8591,
        "reference": "MYCLIENT",
        "name": "MYCLIENT COMPANY \u00a3",
        "allocated_status": "",
        "created_at": "2016-12-02 09:31:00",
        "order_date": "2016-12-02",
        "cust_order_number": "",
        "del_name": "",
        "consignment": "",
        "despatch_date": "0000-00-00",
        "notes_2": ""
    }],
    [],
    [{
            "id": 11691,
            "qty_ordered": 1,
            "qty_delivered": 0,
            "sales_order_id": 8591,
            "due_date": "2016-12-30",
            "stock_code": "ABC-ABDCDE-01",
            "record_deleted": 0,
            "updated_at": null,
            "unit_price": 0,
            "sales_order_item_id": null,
            "comment": null,
            "created_at": null,
            "firmware_version": null,
            "units_assigned": null
        },

        {
            "id": 11692,
            "qty_ordered": 1,
            "qty_delivered": 0,
            "sales_order_id": 8591,
            "due_date": "0000-00-00",
            "stock_code": "MISCELLANEOUS",
            "record_deleted": 0,
            "updated_at": null,
            "unit_price": 232,
            "sales_order_item_id": null,
            "comment": null,
            "created_at": null,
            "firmware_version": null,
            "units_assigned": null
        }
    ]
]

理论上我只需要访问它,因为数组result是:

result[0] // sales order details
result[2] // line items = array of objects

所以

result[0].reference == 'MYCLIENT'

result[2][0].stockcode == 'ABC-ABDCDE-01

但它不会让我这样做。如果我console.log(result[0])结果为[,则console.log(result[0][0].id)结果为undefined

我做错了什么?

3 个答案:

答案 0 :(得分:2)

要么你需要说你的回答是像你这样的ajax中的Json

 dataType: 'json'

或者在得到回复之后你必须将它转换成json对象

response = JSON.parse(response);

答案 1 :(得分:2)

从问题的最后一行看来,您的result仍然是一个字符串。

尝试JSON.parse(result)

答案 2 :(得分:0)

我想你只是错过了关卡。它的参考也在第二级。所以你需要访问它:

console.info(result[0][0].reference)