laravel 如何在laravel中返回json响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40537415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to return json response in laravel
提问by leo
this is my controller:
这是我的控制器:
public function index(Request $request)
{
$items = Post::latest()->paginate(5);
$cmnt = Comment::all();
return response()->json(array('posts'=>$items,'comment'=>$cmnt));
}
this my ajax request
这是我的 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);
}
why i am getting error ?? help me out of this plzz
为什么我收到错误?帮我摆脱这个plzz
回答by pankijs
laravel returns json by default if it doesn't return view, in your case index() should return:
如果 laravel 不返回视图,它默认返回 json,在你的情况下 index() 应该返回:
return ['posts' => $items,'comment' => $cmnt];
also I don't think this is correct
我也不认为这是正确的
{{route('post_status.index')}}
probably should be
大概应该是
{{ url('post_status/index') }}
回答by Alylson Monteiro
You can use the type of response from the server.
您可以使用来自服务器的响应类型。
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);
}