достичь элементов массива php в json - PullRequest
3 голосов
/ 15 августа 2011

Я возвращаю массив из php в json

вот массив 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??
});

Ответы [ 2 ]

8 голосов
/ 15 августа 2011

Вы можете перебрать объект, используя .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 голосов
/ 15 августа 2011

в соответствии с документацией на jQuery вы можете сделать

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...