如何循环json字符串

时间:2019-02-13 10:45:07

标签: javascript php jquery json ajax

我这样从PHP返回数据。

$return['fillable'] = [
    'field_one',
    'field_two',
    'field_three',
    'field_four',
    'field_five',
];

$json = json_encode($return);

return $json;

现在在我的ajax响应中,我想循环填充数组。

$.ajax({
    'type': "GET",
    'global': false,
    'dataType': 'json',
    'url': "/commission-process/"+$('#token').val(),
    'data': {'ajax': true},
    'success': function (data) {

        // how to loop my return array data.

    }
});

我的问题是,我想循环打印这样的可填充数组。

field_one
field_two
field_three
field_four
field_five

谢谢。

2 个答案:

答案 0 :(得分:1)

由于我不知道您是要使用PHP还是Java脚本来遍历它,所以这两者都是结果。

PHP: 您必须先像这样解码json:

$array = json_decode( $json, true );

然后,您可以像遍历其他任何数组一样遍历它。

Javascript:

for(i = 0; i<data.fillable.length; i++)
{
    console.log(data.fillable[i]);
}

答案 1 :(得分:0)

$.ajax({
'type': "GET",
'global': false,
'dataType': 'json',
'url': "/commission-process/"+$('#token').val(),
'data': {'ajax': true},
'success': function (data) {

    var json = JSON.parse(data);
    $.each(json, function(i,e){
       console.log(i);
       console.log(e);
    });
}

});