PHP中JSON Obj的空白页(Blank Page for JSON Obj in PHP)

当我打印出数组时,它没关系,它打印,但它不打印为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); } ?>

When I print out as array, It's OK, it prints, but it doesn't print as JSON Objects, instead, It returns blank page

Thanks in Advance

<? 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); } ?>

最满意答案

由于不同的因素,它可能是空白的,事实上,如果一切顺利,您的代码只会输出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); ?>

It could be blank due to different factors, in fact your code would only output the JSON if everything went fine as expected. You only coded the happy cases, you need to include all possible condition to your 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); ?>

更多推荐