PHP中JSON Obj的空白页

时间:2016-02-15 02:59:46

标签: php html json

当我打印出数组时,没关系,打印出来,但不打印为JSON Objects,而是返回空白页

先谢谢

<?

require_once('include/db_functions.php');

if($_GET){
    $ad = stripslashes($_GET["ad"]);
    try{
        $dbFuncs = new db_functions();
    }catch(PDOException $e){
        print $e -> getMessage();
    }

    $ss = $dbFuncs->getCategoryLista($ad);

    foreach($ss as $ccc){
        $data[] = array(
            "ID" => $ccc['CategoryID'],
            "Name" => $ccc['CategoryName']
        );
    }        
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
}
?>

1 个答案:

答案 0 :(得分:0)

由于不同的因素,它可能是空白的,实际上如果一切顺利,你的代码只会输出JSON。您只编写了快乐案例,您需要在json中包含所有可能的条件:

<?php
header("Content-type: application/json; charset=utf-8");
require_once('include/db_functions.php');
$data = array();
if(isset($_GET["ad"])){
    $ad = stripslashes($_GET["ad"]);
    try{
        $dbFuncs = new db_functions();
        $ss = $dbFuncs->getCategoryLista($ad);

        if(count($ss) != 0){
            $data['success'] = true;
            foreach($ss as $ccc){
                $data['data'][] = array(
                    "ID" => $ccc['CategoryID'],
                    "Name" => $ccc['CategoryName']
                );
            }    
        }else{
            $data['success'] = false;
            $data['data'] = 'count() == 0';
        }
    }catch(PDOException $e){
        print $e -> getMessage();
        $data['success'] = false;
        $data['data'] = 'error = '.$e -> getMessage();
    }
}else{
    $data['success'] = false;
    $data['data'] = '$_GET["ad"] is not set';

}
echo json_encode($data);
?>