Jquery Laravel 7通过json将值从ajax导出到blade到for循环
我在JSON响应中有一个来自DB的ajax调用,如Jquery Laravel 7通过json将值从ajax导出到blade到for循环,jquery,ajax,laravel,Jquery,Ajax,Laravel,我在JSON响应中有一个来自DB的ajax调用,如 0: {id: 1, name: "nancy", cost: 100, quantity: 4, barcode: 12345, category_id: 1,…} 1: {id: 3, name: "elissa", cost: 60, quantity: 3, barcode: 98987, category_id: 1,…} 2: {id: 4, name: "nancy",
0: {id: 1, name: "nancy", cost: 100, quantity: 4, barcode: 12345, category_id: 1,…}
1: {id: 3, name: "elissa", cost: 60, quantity: 3, barcode: 98987, category_id: 1,…}
2: {id: 4, name: "nancy", cost: 100, quantity: 32, barcode: 99999, category_id: 1,…}
3: {id: 7, name: "new one", cost: 200, quantity: 12, barcode: 66778, category_id: 1,…}
4: {id: 10, name: "new begama", cost: 70, quantity: 6, barcode: 10001, category_id: 1,…}
我知道了长度
success: function (result) {//alert(typeof (result)); alert(result.length);) }),
如何在Blade.php中对它们进行forloop如果您想在
Blade
中严格循环这些,则需要在响应中传递HTML
,而不是JSON
。否则,您将别无选择,只能在JS
中循环它们
例如,您需要创建一个视图文件,其内容如下:
public function salesHiddenCoffee(Request $request)
{
$category_id = $request->get('category_id');
$products = Product::where('category_id', $category_id)->get();
$view = view('make.a.view.the.html.above.in.it.then.put.the.path.here', ['products' => $products]);
$html = $view->render();
return ['success' => true, 'html' => $html];
}
使用下面的html创建一个视图,然后将这个新文件的路径放在下面的控制器方法中
@foreach($data as $item)
{{$item->name}}
@endforeach
然后在控制器中执行如下操作:
public function salesHiddenCoffee(Request $request)
{
$category_id = $request->get('category_id');
$products = Product::where('category_id', $category_id)->get();
$view = view('make.a.view.the.html.above.in.it.then.put.the.path.here', ['products' => $products]);
$html = $view->render();
return ['success' => true, 'html' => $html];
}
当然,您需要更改JS来消化HTML
响应
success: function (result) {
if(result.html != undefined) {
$(container_you_want_the_html_to_go).html(result.html);
}
}),
或者
let container = $('#ID_of_your_container');
$.each(result, function (i, item) {
$(container).append('<div>' + item.name + '</div>');
});
let container=$(“#ID_of_your_container”);
$。每个(结果、功能(i、项目){
$(容器)。追加(“”+item.name+“”);
});
我在鬃毛视图中选择了类别标签。取决于它调用ajax来查看所拥有的产品,可以使用render(),或者在jquery中编写模板并使用appendTo()??听起来你有点过于复杂了-你能分享你的控制器方法代码吗?``公共函数SalesHiddenChofe(Request$Request){$category\u id=$Request->get('category_id');//dd($category_id);$products=Product::where('category_id','LIKE',$category_id)->get();return response()->json($products);}``你是说我必须创建一个新的视图刀片并为产品创建一个模板,然后将视图呈现到主视图?