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 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解