0
的ajax
電話後,我php
腳本echo
s出一個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
你可能要張貼由客戶端收到的JSON。 – user1032531
此外,如果您更改爲'退出(json_encode($ items_array));'?會發生什麼? – user1032531
而且,在回聲之前添加'header('Content-Type:application/json');''。 – user1032531