0

我正在尝试解析从$.post().

[{"id":"1","text":"USD"},
 {"id":"2","text":"CNY"},
 {"id":"3","text":"PHP"},
 {"id":"4","text":"AUD"},
 {"id":"5","text":"SGD"},
 {"id":"6","text":"JPY"}]

使用这种方法Jquery,循环一个json数组

我做了这样的事情:

$.post(
    base_url+'cgame/currency',
    { gameID: gameID },
    function(data) {
        $(this).html();
        $.each(data,function(idx, obj) {
            $(obj).each(function(key, value) {
                console.log(key + ": " + value);
            });
        });
    }
);

但它给了我错误:

未捕获的类型错误:无法使用 'in' 运算符在 in 中搜索 '120'[{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]

我也试过:

$.post(
    base_url+'cgame/currency',
    { gameID: gameID },
    function(data) {
        $(this).html();
        $(data).each(function(idx, obj) {
            $(obj).each(function(key, value) {
                console.log(key + ": " + value);
            });
        });
    }
);

但它也给了我错误:

未捕获的错误:语法错误,无法识别的表达式:[{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]

我应该怎么做?

4

4 回答 4

2

您的数据以数组的形式出现,因此您需要遍历每个索引,然后获取值。所以你可以替换这个: -

 $(obj).each(function(key, value) {
     console.log(key + ": " + value);
 });

和 :-

 $.each( obj, function( key) {
     console.log( obj[key].id + ':' + obj[key].text);
 });

或者你可以这样做: -

 $.each( obj, function( key, value ) {
     console.log( value.id + ':' + value.text);
 });

key 是数组的索引。它将返回 0,1,2..

于 2013-10-21T08:04:04.487 回答
1

我认为传递给您的成功回调函数的参数是字符串类型。将其更改为:

 function(data) {
var parsedData = JSON.parse(data);
    $(this).html();
    $.each(parsedData ,function(idx, obj) {
        $(obj).each(function(key, value) {
            console.log(key + ": " + value);
        });
    });
}
于 2013-10-21T07:46:18.767 回答
1
 function(data) {
    var value = JSON.parse(data);
    $.each(value ,function(idx, obj) {
       console.log("id : "+obj.id+" "+text:"+obj.text);
    });
 }
于 2013-10-21T07:58:15.480 回答
0

试试这个

$.post(base_url+'cgame/currency',{ gameID: gameID },
 function(data) {
    $(this).html(); //<-- becareful $(this) might not be the element you think it is
    $.each(data,function(idx, obj) {
        console.log( "id : " + obj.id);
        console.log( "text: " + obj.text);
   });
 },'JSON');
于 2013-10-21T07:43:17.507 回答