[英]how can i send json data from my controller to view?
public function getSectionsForClass(Request $request ,$id )
{
$section = Section::all()->where('clas_id',$id);
return response()->json($section);
}
我需要将此json发送到我在表中的视图
@foreach($section as $sec)
{{$sec->section}}
{{$sec->capacity}}
{{$sec->teacher}}
{{$sec->class}}
@endforeach
这是我发送 id 和 url 的 ajax 代码
<script type="text/javascript">
$('#select_id').change(function(){
// alert('hello');
var cid = $(this).val();
if(cid){
$.ajax({
dataType: "json",
url: 'section/index/'+cid,
//data: {'class': cid},
type:"GET",
success: function(response){
console.log ((response));
},error: (error) => {
console.log(JSON.stringify(error));
}
});
}
});
</script>
途中
Route::get('admin/section/index/{id}','SectionController@getSectionsForClass');
预先感谢希望我能得到我的答案
根据 Laravel 文档,您可以直接从您的方法发送json
响应
json 方法会自动将
Content-Type
标头设置为application/json
,并使用json_encode
PHP 函数将给定的数组转换为 JSON:
return response()->json([
// You can pass your array values here
]);
然后你可以从你的 ajax 成功中创建动态表,在特定的 id 中附加该表,例如
success: function(response){
for (var key in response) {
$('#here_table').append( '<tr><td>' + response[key] + '</td></tr>' );
}
}
目前,您将查询生成器的实例作为 json 响应返回。 您还没有执行查询。
要从查询中获取结果,您需要实际执行查询。 在最后添加get()
:
public function getSectionsForClass(Request $request ,$id )
{
$section = Section::where('clas_id', $id)->get();
// ^^^^^^^
return response()->json($section);
}
当然,如果您有很多记录,这可以在分页列表中更好地管理,但您明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.