dongluxin6711 2015-04-11 10:41
浏览 76
已采纳

如何访问从php转换为javascript对象的实体

I am throwing entity object to javascript by ajax

in php

// obtaining object by doctrine2
$lesson = $em->getRepository('Lesson')
    ->findOneBy(array('id' => $myId));

// $lesson->getName(); // I can access the entity property here like this.

//throwing object as json
$response = array("responseCode" => 200,'lesson' => $lesson,"success" => true);
return new Response(json_encode($response),200,array('Content-Type'=>'application/json'));

in javascript

function reloadItems(){
    var url= "http://myajax.com/ajax/";
    $.post(url,something,function(data){
// I got lesson object from php as json here.

// however these doesn't work
//      console.log(data.lesson.name);
//      console.log(data.lesson.getName);

    });

How can I get the each repository data in javascript??

  • 写回答

1条回答 默认 最新

  • dsgsdg206050 2015-04-11 12:20
    关注

    When passed an object, json_encode can only grab the public properties. Methods are ignored completely. Since $lesson is a doctrine entity then I'm sure Lesson::name is either private or protected.

    There are some serializer tools like http://symfony.com/doc/current/components/serializer.html which use reflection to access private/protected variables.

    Or you can use PHP's (>=5.4) json serializer http://php.net/manual/en/jsonserializable.jsonserialize.php

    Something like:

    class Lesson implements \JsonSerializable
    {
      private $name;
    
      public function jsonSerialize() 
      {
        return 
        [
          'name' => $this->name,
        ];
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题