如何返回视图HTML到控制器ajax成功



我想返回整个html到控制器ajax响应。我正在使用render(),但没有得到任何数据到返回方法

下面是我的ajax:
$.ajax({
type: 'GET',
url: '{{url('/filter_each_video')}}',
data : { resolution : myCheckboxes, fps : myCheckboxesfps },
dataType: 'json',
success: function (response) {
console.log(response);

},
error: function (data) {
console.log(data);
// console.log(data);
}
});

下面是实际渲染视图的控制器

function filter_each_video(){
if(request()->ajax()){

$item = Item::whereIn('format', $_GET['resolution'])->get();
$formats = DB::table('items')->select('format')->distinct()->get();
$fps = DB::table('items')->select('fps')->distinct()->get();
$data['item_count'] = $item;
$data['item'] = $item;
$data= $this->sellWise($data);
$data= $this->starWise($data);
$data= $this->dateWise($data);
return view('frontend.pages.videos_for_each_filter', compact('data','formats','fps'))->render();
}
}

下面是视图文件,从我设置值和整个html返回到控制器的ajax响应

<?php
$html ="";
$html.= '<div class="row video-list">';
foreach($data['item'] as $video){
$html.= '<div class="item video-item сol-12 col-md-6 col-lg-3 text-white mb-4 pull-left">
<div class="item-wrapper display-7">
<div class="item-img">Video Name</div>
</div>
</div>';
}
$html.= '</div>';
return $html;
?>

如果有人知道我做错了什么取回html内容到控制器然后请让我知道

我想把整个html返回给ajax响应

(1)你试过response($output, 200, $headers)吗?

$html = view('frontend.pages.videos_for_each_filter', compact('data','formats','fps'))
->render();
Log::debug('Rendered HTML', ['html'=>$html]);
return response($html,200);

检查您的/storage/logs以再次检查$html是否正确。

(2)你也可以尝试使用JSON:
return response()->json(['html' => $html]); 

客户端

console.log("res is ", response.data.html);

另一个注意事项是,您应该验证请求数据,而不是直接使用$_GET。你的控制器方法应该像这样:

use IlluminateHttpRequest; // (? From memory, maybe check the namespace)
public function filter_each_video(Request $request)
{
$request->validate(['resolution' => 'required|string']);
if( $request->ajax() ){
$item = Item::whereIn('format', $request->resolution)->first();
// ... cont'd
}
}

如果你得到一个空的响应,扔一些Log::debug语句在那里,并找出你失去响应的地方。

最新更新