我创建了一个评论系统,允许用户在产品中添加评论并显示评级星级。因此,如果用户对产品评分为 4 分,则应显示 4 颗满星和一颗空星(就像其他评论系统一样)。如何根据用户评论循环显示每个评分星级?
这是从 Controller 接收到的数据 (console.log())
data: Array(2)
0: "4" //This is the rating for user 1
1: "3" // This is for user 2
length: 2
Controller
$products = Product::where('id','=',$id)->with('reviews.user')->get();
$data = array();
foreach ($products as $product)
{
foreach ($product->reviews as $review){
$data []= $review->rating;
}
}
return response()->json(['code' => 200,'data' => $data]);
Ajax
function UserRateStars() {
$.ajax({
type: "GET",
url: '{{route('userRate.stars ', $id)}}',
success: function(data) {
document.getElementById("UserRateStars").innerHTML = UserRateStars(3.6);
// Round to nearest half
var rating = Math.round(data * 2) / 2;
let output = [];
console.log(data);
// Append all the filled whole stars
for (var i = rating; i >= 1; i--)
output.push('<div >full star</div> ');
// If there is a half a star, append it
if (i == .5) output.push('<div >half star</div> ');
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--)
output.push('<div>empty star</div> ');
return output.join('');
}
});
}
UserRateStars();
最佳答案
这里是您的代码中需要的更改..
<script type="text/javascript">
function UserRateStars() {
$.ajax({
type: "GET",
url: '{{route('userRate.stars ', $id)}}',
success: function(data) {
var html = [];
data.data.forEach(function (item, index) {
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "user"+index);
newDiv.innerHTML = SingleUserRateStars(item);
html.push(newDiv.outerHTML);
});
document.getElementById("UserRateStars").innerHTML = html.join('');
}
});
}
UserRateStars();
function SingleUserRateStars(rating) {
// Round to nearest half
rating = Math.round(rating * 2) / 2;
let output = [];
console.log(rating);
// Append all the filled whole stars
for (var i = rating; i >= 1; i--)
output.push('<div style="display:inline-block" >full star</div> ');
// If there is a half a star, append it
if (i == .5) output.push('<div style="display:inline-block" >half star</div> ');
// Fill the empty stars
for (let i = (5 - rating); i >= 1; i--)
output.push('<div style="display:inline-block" >empty star</div> ');
return output.join('');
}
</script>
我假设您使用的内部函数是生成单个用户的评级和您从服务器作为数组生成的用户数据。例如 ["2","4","4.5"]
我将其拆分到外部并循环每个用户评级,并将每个评级包装在一个 div 内并附加到您的目标 div。希望这可以帮助您。
关于javascript - 如何显示评分星级 Laravel 和 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837454/