如何从php返回的json解析数组

时间:2012-10-24 00:22:46

标签: php arrays json

我有一个index.html文件,它调用main.php,它返回一个json对象就好了。

main.php返回此

{
    "products": [
        {
            "id": "1",
            "txt": "Bar",
            "image": "",
            "page": ""
        },
        {
            "id": "2",
            "txt": "Car",
            "image": "",
            "page": ""
        },
        {
            "id": "3",
            "txt": "Far",
            "image": "",
            "page": ""
        }
    ],
    "success": 1
}

在Java中有json.getJSONArray(TAG_PRODUCTS);

但....我在这里使用HTML和JavaScript ... 所以在我的html文件中,我有以下内容 如何从json返回的数据中提取产品数组?

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'http://localhost:8888/HelloWorld/main.php',
    contentType: "application/json; charset=utf-8",
    success: function (data) { 
        var names = data
        $('sa_content').append('<select name="input_4">');
        $.each(data, function(index, element) {

            alert( "index: " + index + ", element.cf_id: " + element );

        });
        $('sa_content').append('</select>');
    },
    error: function(){
        $('#sa_content').append('<li>There was an error loading the feed');
    }
});

当我运行index.html页面时,我收到以下警告

index = products, element =  [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

index = success, element =  1

那么如何将产品数组拉出json并迭代它以获取id,txt,image,page的值?

提前感谢您的时间。 迪安-O

4 个答案:

答案 0 :(得分:3)

尝试将此作为成功函数使用:

function (data) {
    var products = data.products;

    for (var i = 0; i < products.length; i++) {
        var product = products[i];
        alert(product.id + " " + product.txt + " " + product.image + " " + product.page);
    }
}

它应该遍历所有产品并提醒您数据。 然后,您可以修改代码以满足您的需求。

答案 1 :(得分:0)

如果您确定代码是安全的,您可以使用JSON.parse,也可以只使用eval('(' + json + ')');

答案 2 :(得分:0)

您正在获得一系列产品,因此您希望迭代该数组:

success: function (data) { 
    var names = data

    for(i = 0; i < data.products.length; i++) {
        //Do what you want.
        var id = data.products[i].id;
    }
}

答案 3 :(得分:0)

如果你的页面只返回json,那么从jquery ajax返回的XHR对象应该包含一个从该数据构造的javascript对象。如果不是这种情况,则页面出现问题,例如返回的不仅仅是json编码的字符串。

相关问题