【问题标题】:Displaying JSON variable value in Laravel在 Laravel 中显示 JSON 变量值
【发布时间】:2014-04-18 20:07:33
【问题描述】:

我在最近的 Laravel 4.1 项目中收到了这个,我相信它会返回 JSON,

{"id":5,"owner":"2","message":"What a wonderful shoot today in Belgium!","post_at":"2","created_at":"2014-02-25 15:05:50","updated_at":"2014-02-25 19:05:50"}

但我通常可以这样显示:

echo $post->id;

但不知何故,它没有返回任何“5”。 但是当我使用$post->toArray(); 转换为数组并尝试使用echo $post['id']; 查看时,它成功返回“5”。

使用echo $post->id; 返回其价值的最佳方式是什么?我还尝试使用$post->toJSON(); 确保变量为 JSON,但它仍然返回空。

【问题讨论】:

  • 如果您想像访问对象一样访问它,为什么它会以 JSON 形式返回?话虽这么说,因为它是 JSON,json_decode,这就是你要找的东西:php.net/json_decode。这会将 JSON 转换为 stdClass 对象。
  • 太棒了。它运作良好!我从带有查询static::whereIn('owner', $meandfriends)->orderby('updated_at','desc')->get() 的服装模型类中获得了 JSON

标签: arrays json laravel


【解决方案1】:

检查一下

$post = Post::where('id','=',5)->get()
(不要忘记 get()

$post = Post::where('id',5)->get()
(不要忘记 get()

$post = Post::find(5);

回复可能:

响应::json($post);

【讨论】:

  • 您的查询已经过测试并且有效,但这不是我的意思,但是谢谢我现在意识到了,我应该像这样返回:if(!is_null($stream = static::whereIn('owner', $meandfriends)->orderby('updated_at','desc')->get())){ return json_decode($stream); } 而不是:if(!is_null($stream = static::whereIn('owner', $meandfriends)->orderby('updated_at','desc')->get())){ return $stream; }
【解决方案2】:
   $.get('url', {'id': id}, function (obj) {
     var te=obj.id;
     alert(te);
   });

【讨论】:

  • 他想在模板中直接做,而不是用 jQuery。
猜你喜欢
  • 2020-10-07
  • 2018-11-12
  • 2020-01-11
  • 1970-01-01
  • 2017-07-26
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多