首先,下面是我如何将刚做的评分返回到服务器的。在my$(document).ready事件处理程序中,我向页面中id包含ddlRatingOptions的所有<select>元素添加更改事件处理程序。在事件处理程序中,我获得与更改的下拉列表相关联的ProductID和Rating。然后我对服务器进行ajax回调,传递值。
$("#products select[id*='ddlRatingOptions']").change(function () {
// Determine the ProductID for the product that was just rated
var productId = $(this).attr('ProductID');
var rating = $(this).val();
// Send the rating and productId back to the server
$.ajax({
url: '<%=Page.ResolveClientUrl("~/Services/RateProduct.ashx") %>',
data: {
ProductID: productId,
Rating: rating
},
cache: false,
});
});
这很有效。
我现在做的很好,但感觉像黑客。我希望有更简单的方法。简而言之,我找到<div>,然后在发出ajax请求时将其id发送给服务器。服务器端代码会将其返回(以及平均评级)。然后,在success事件处理程序中,通过该回显id找到<div>,并相应地更新其文本。
$("#products select[id*='ddlRatingOptions']").change(function () {
...
// Determine the "Current Average Rating" element that needs to be updated after the ajax call completes
var currentRating = $(this).parent().siblings(".currentRating");
$.ajax({
url: '<%=Page.ResolveClientUrl("~/Services/RateProduct.ashx") %>',
data: {
ProductID: productId,
Rating: rating,
CurrentRatingId: currentRating.attr('id')
},
cache: false,
dataType: 'json',
success: function (results) {
// Update the current rating with the new average rating
$("#" + results.CurrentRatingId).text(results.AverageRating + ' Stars');
}
});
});
有没有更干净的方法?
谢谢!