2011-08-15 80 views
3

我返回數組的數組從PHP到JSON達到PHP數組元素

這裏的PHP數組

$cities = array(); 
while($row = mysql_fetch_array($result)){ 
    $cityRow= array('cityNo'=>$row['city_no'], 'cityName'=>$row['city_name']); 
    $cities[]=$cityRow; 
} 
echo json_encode($cities); 

這裏的JSON

$.getJSON("controllers/Customer.controller.php",param,function(result){ 
    // what should I write here to reach the array elements?? 
}); 

回答

8

您可以在對象上使用迭代.each

$.getJSON("controllers/Customer.controller.php", param, function(json){ 

    // loop over each object in the array 
    // 'i' is the index of the object within the array 
    // 'val' (or this) is the actual object at that offset 
    $.each(json, function(i, val) { 
     console.log(val.cityNo); // same as this.cityNo 
     console.log(val.cityName); // same as this.cityName 
    }); 
}); 
+0

我提出警告,而不是CONSOL,CZ我用notpad ++,但它不與城市名稱和全城戒備沒有,甚至會造成(城市名稱及編號)顯示在螢火蟲consol作爲迴應的要求! – palAlaa

+0

也許JSON無效?你可以將它粘貼到www.jsonlint.com並檢查錯誤嗎?下面是一個演示,以證明上述工作:http://jsfiddle.net/karim79/8uMnm/ – karim79

+1

@Alaa - 「所有字符串,無論它們是屬性還是值,都必須用雙引號括起來」。 http://api.jquery.com/jQuery.getJSON/ – karim79

0

根據documentation on jQuery你可以做

 
$.getJSON("controllers/Customer.controller.php",param,function(result){ 
    alert(result.cityNo); 
    alert(result.cityName); 
}); 

+1

它是一個對象數組,不是單個對象,所以需要某種循環。 – karim79

+0

@ karim79,很對。錯過了那一點 – trailmax