我正在尝试使用 Ajax 显示数据库中的名称,并且在 Controller 中使用 foreach 循环,但它只返回一个名称而不是两个(它无法正确循环)。我已经看到了一些答案,人们建议在 View 中使用 foreach 但就我而言,我在 View 中使用 Ajax 如何在 Ajax 中使用 foreach 或者有什么方法可以显示所有名称?
我尝试过使用这些,但它返回一个名称而不是两个。
$data = [];
$data[] = $review->user->name;
Controller
$products = Product::where('id','=',$id)->with('reviews.user')->get();
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data = $review->user->name;
dd($data); //This returns one name
}
}
Ajax
<script >
function userRatingname() {
$.ajax({
type: "GET",
url: '{{route('userRating.name ', $id)}}',
success: function(data) {
$('#userRatingname').html('<div>' + data + '</div>');
}
});
}
userRatingname();
</script>
最佳答案
您一次又一次地覆盖 $data
的值,因此它将返回最后一个用户名。
您需要将 $data = [];
置于循环之外。并在循环内使用 $data[] = $review->user->name;
:
$products = Product::where('id','=',$id)->with('reviews.user')->get();
$data = array(); // defined the $data here out of loop
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data []= $review->user->name; // push the username to $data
}
}
// Or you can use whereIn for User:
$data = User::whereIn('id', ProductReview::where('product_id',$id)->pluck('user_id'))->pluck('name')->toArray();
return response()->json(['code' => 200, 'data' => $data]);
更改你的ajax代码:
function userRatingname() {
$.ajax({
type: "GET",
url: '{{route('userRating.name ', $id)}}',
success: function(data) {
var html = '';
data['data'].forEach(function(name) {
html += '<div>' + name + '</div>'
});
$('#userRatingname').html(html);
}
});
关于javascript - Controller 中的 Foreach 仅返回一个输出 Laravel 和 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60828924/