2015-12-14 89 views
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 
+0

你可能要張貼由客戶端收到的JSON。 – user1032531

+0

此外,如果您更改爲'退出(json_encode($ items_array));'?會發生什麼? – user1032531

+0

而且,在回聲之前添加'header('Content-Type:application/json');''。 – user1032531

回答

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