如何传递 JSON 数据以在 Laravel 中查看

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39308057/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:24:24  来源:igfitidea点击:

how to pass JSON data to view in laravel

jsonlaravelview

提问by nouman

I want to pass this JSON data to some view but don't know how its works.

我想将此 JSON 数据传递给某个视图,但不知道它是如何工作的。

I have used, make view also, and convert this data to JSON and pass other way but it didn't work

我也使用过,制作视图,并将这些数据转换为 JSON 并通过其他方式传递,但它没有用

$items = Items::all();
return response()->JSON($items);

e.g view is items.create

例如观点是 items.create

回答by Toney Dias

For Laravel ver 4.2, You can pass your data to your bladeview with a variable (eg:$data) having an array which will be used in your blade.

对于 Laravel 4.2 版,您可以使用变量(例如:$data)将数据传递到刀片视图,该变量具有将在刀片中使用的数组。

$flag is variable being used in the JS part of your code, so you can pass that also as an array: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);

$flag 是在代码的 JS 部分中使用的变量,因此您也可以将其作为数组传递: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);

In your controller return the view:

在您的控制器中返回视图:

 return Response::json(['view' => View::make('yourbladename', $data)->render(), 'flag'=>$flag]);

In your JS use the data variables as:

在您的 JS 中,将数据变量用作:

function(data){     
 $('#DivToAppendHTML').append(data.view);                    //this appends html blade to the Div having the ID DivToAppendHTML
       if(data.flag == 1){                                  //this uses the second variable passed in controller for any other purpose
                       $('.classname').remove();
        }
}

回答by Alexey Mezenin

If you want to create JSON response, you need to convert collection to an array:

如果要创建JSON 响应,则需要将集合转换为数组:

$items = Items::all()->toArray(); // $items is array now
return response()->json($items);

If you want to pass some JSON datato a view, do this:

如果要将一些JSON 数据传递给视图,请执行以下操作:

$items = Items::all()->toJson();
return view('items.create', compact('items'));