0

我有一个调用 main.php 的 index.html 文件,它返回一个 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

那么如何将 products 数组从 json 中拉出并遍历它以获取 id、txt、image、page 的值?

在此先感谢您的时间。院长-O

4

4 回答 4

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);
    }
}

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

于 2012-10-24T00:28:57.093 回答
0

您可以使用JSON.parse, 或者仅eval('(' + json + ')');在您确定代码是安全的情况下使用。

于 2012-10-24T00:28:15.353 回答
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;
    }
}
于 2012-10-24T00:29:08.537 回答
0

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

于 2012-10-24T00:31:49.193 回答