循环遍历多维数组输出单个字符

时间:2015-12-14 20:32:20

标签: javascript php arrays json multidimensional-array

ajax来电之后,我的php脚本echo出了一个json_encode d多维数组。当我在我的javascript中循环遍历数组时,它会迭代每个单独的字符而不是顶级数组元素。为什么呢?

JS

    $('.test').on('click',function(){
        $.ajax({
            url: 'http://domain.com/my/script,
        }).done(function(multidimensionalArray) {
            console.log(multidimensionalArray);         //outputs the seemingly correct array
            console.log(multidimensionalArray.length);  //outputs number of characters (instead of the expected 20...)
        })
    });

PHP

public function calledByAjax() {
    $items = namespace\items\GetList::getAll(array(
        'limit' => 20 // This appropriately limits the results to 20, which is why 20 is expected above in the js
    ));

    $items_array = array();
    foreach($items as $key=>$item){
        $temp = array (
            'attr1' => $item->getPrivateVar1(),
            'attr2' => $item->getPrivateVar2(),
            'attr3' => $item->getPrivateVar3(),
        );
        $items_array[$key] = $temp;
    }
    echo json_encode($items_array);
    exit(0);
}

的console.log(multidimensionalArray)

[{"attr1":"The variable","attr2":"the variable","attr3":"the variable"},...
...so on for 20 items...
]

的console.log(multidimensionalArray.length)

1562

1 个答案:

答案 0 :(得分:0)

您没有使用对象但使用字符串。

您需要确保将PHP脚本(字符串)的返回输出解析为json。最简单的方法是指定dataType

$('.test').on('click',function(){
    $.ajax({
        url: 'http://domain.com/my/script',
        dataType: 'json'   // the expected data type is json, 
                           // jQuery will parse it automatically
    }).done(function(multidimensionalArray) {
        console.log(multidimensionalArray);         //outputs the seemingly correct array
        console.log(multidimensionalArray.length);  //outputs number of characters (instead of the expected 20...)
    })
});