【问题标题】:reach php array elements in json到达json中的php数组元素
【发布时间】:2011-08-15 01:28:29
【问题描述】:

我将一个数组从 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??
});

【问题讨论】:

    标签: php jquery ajax json


    【解决方案1】:

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

    【讨论】:

    • 我发出警报而不是 consol,cz 我使用 notpad++,但它不会用城市名称和城市编号发出警报,甚至结果(城市名称和编号)都显示在 firebug 控制台中作为响应请求!
    • 也许 JSON 无效?你能把它粘贴到 www.jsonlint.com 并检查它是否有错误吗?这是一个小演示,只是为了证明上述工作:jsfiddle.net/karim79/8uMnm
    • @Alaa - “所有字符串,无论是属性还是值,都必须用双引号括起来”。 api.jquery.com/jQuery.getJSON
    • 你能告诉我有一个显示 javascript 结果的控制台的 IDE 是什么吗?
    • @Alaa - 您只需要 FireFox 或 Chrome(还有其他),但我主要使用这些。 Chrome 有一个内置的“检查器”,而 firefox 有 firebug 插件 (www.getfirebug.com)。我想你会发现那些是救生员。
    【解决方案2】:

    根据documentation on jQuery你可以做

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

    【讨论】:

    • 这是一个对象数组,而不是单个对象,因此需要某种循环。
    猜你喜欢
    • 2013-07-20
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多