在json中访问PHP数组元素


reach php array elements in 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??
});

您可以使用.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
    });
});

根据jQuery的文档你可以做

<>之前.getJSON美元("控制器/Customer.controller.php"、参数、功能(结果){警报(result.cityNo);警报(result.cityName);});