【问题标题】:how to return json response in laravel如何在laravel中返回json响应
【发布时间】:2017-03-25 01:27:04
【问题描述】:

这是我的控制器:

public function index(Request $request)
    {
        $items = Post::latest()->paginate(5);
        $cmnt = Comment::all();

        return response()->json(array('posts'=>$items,'comment'=>$cmnt));
    }

这是我的 ajax 请求

function getPageData() {
      $.ajax({
        dataType: 'json',
        url: "{{route('post_status.index')}}",
        data: {page:1}
      }).done(function(data){
            manageRow(data.data);
      });
    }
function manageRow(data) {
          console.log(data.comment);
}

为什么我会出错?? 请帮我解决这个问题

【问题讨论】:

  • “为什么我会出错”什么错误?
  • 实际上它什么也没告诉我.....没有任何价值
  • @leo 你试过在控制台中查看吗?在您对答案的评论中,您还谈到了多个对象?你能解释一下你在你的问题中想要做什么吗?
  • 我想使用 ajax 响应从我的控制器返回 $items 和 $cmnt 这两个对象

标签: php json ajax laravel


【解决方案1】:

laravel 如果不返回视图,默认返回 json,在你的情况下 index() 应该返回:

return ['posts' => $items,'comment' => $cmnt];

我也不认为这是正确的

{{route('post_status.index')}}

应该是

{{ url('post_status/index') }}

【讨论】:

  • 当我返回一个对象时路由是好的,但是当我想返回多个对象时它不起作用
【解决方案2】:

您可以使用来自服务器的响应类型。

function getPageData() {
    $.ajax({
      dataType: 'json',
      url: "{{route('post_status.index')}}",
      type: 'GET'
      data: {page:1}
    }).done(function(data){
        manageRow(data.data);
    });
}

function manageRow(data) {
    console.log(data.comment);
}

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2020-02-20
    • 2016-12-07
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多