Ajax调用返回一个空对象数组

时间:2018-11-07 09:02:34

标签: php jquery ajax oop

Am使用php的OOP,从数据库中获取数据。 数据获取良好,但是当我进行ajax调用时,它返回一个空对象数组。如何使对象返回数据

在对json_encoding之前获取数据库结果

Array ( [0] => CategoryModel Object ( [id:CategoryModel:private] => 1 [code:CategoryModel:private] => cat001 [name:CategoryModel:private] => laptop [date:CategoryModel:private] => 2018-11-05 15:33:21 [owner:CategoryModel:private] => OwnerModel Object ( [companyName:OwnerModel:private] => [id:PersonModel:private] => 1 [code:PersonModel:private] => [firstname:PersonModel:private] => [lastname:PersonModel:private] => [username:PersonModel:private] => [email:PersonModel:private] => [password:PersonModel:private] => [date:PersonModel:private] => [mobile:PersonModel:private] => [fullname:PersonModel:private] => Galiwango Fahad [account_type:PersonModel:private] => ) [status:CategoryModel:private] => 0 ) [1] => CategoryModel Object ( [id:CategoryModel:private] => 2 [code:CategoryModel:private] => cat002 [name:CategoryModel:private] => pen [date:CategoryModel:private] => 2018-11-05 16:05:29 [owner:CategoryModel:private] => OwnerModel Object ( [companyName:OwnerModel:private] => [id:PersonModel:private] => 1 [code:PersonModel:private] => [firstname:PersonModel:private] => [lastname:PersonModel:private] => [username:PersonModel:private] => [email:PersonModel:private] => [password:PersonModel:private] => [date:PersonModel:private] => [mobile:PersonModel:private] => [fullname:PersonModel:private] => Galiwango Fahad [account_type:PersonModel:private] => ) [status:CategoryModel:private] => 0 ) )

php代码 用于检索和编码数据的

<?php

require_once("../services/CategoryService.php");
$categoryService = new CategoryService();
$categoryArray =  $categoryService->selectAllCategoryDetails();
if(count($categoryArray)>0){
// echo print_r($categoryArray);
  echo json_encode($categoryArray);


}else{
  echo 0;
}

?>

javascript

$.ajax({
    type: "POST",
    url: ".././com.flex_audit/controllers/fetchAllCategoriesController.php",
    data: "",

    success: function (responseData) {
        if(responseData!=0){
            var categoryObjArr = JSON.parse(responseData);
            console.log(categoryObjArr);
            console.log(categoryObjArr[0]);
            console.log(categoryObjArr[0]["id"]);
        }else{
            $("#alertMessage").text(" categories not found ");
        }
       // console.log(responseData);    
    }
    ,
    error:function(error){
      alert("an error occured "+error);
    }
});

  });

控制台结果

(2) [{…}, {…}]
 {}
 undefined

为什么响应返回空对象

1 个答案:

答案 0 :(得分:0)

因为对象的所有属性都是私有的  *在将类属性设为公开而非私有后才起作用*

来自

private $id,$code,$name,$date,$owner,$status;

public $id,$code,$name,$date,$owner,$status;