代码之家  ›  专栏  ›  技术社区  ›  Scott Mitchell

jqueryajax调用完成后更新div

  •  1
  • Scott Mitchell  · 技术社区  · 14 年前

    首先,下面是我如何将刚做的评分返回到服务器的。在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');
            }
        });
    });
    

    有没有更干净的方法?

    谢谢!

    2 回复  |  直到 14 年前
        1
  •  3
  •   Andy E    14 年前

    currentRating 变量,所以这只是以后重新使用该变量的情况,而不是查找ID:

    $("#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").eq(0);
    
        $.ajax({
            url: '<%=Page.ResolveClientUrl("~/Services/RateProduct.ashx") %>',
            data: {
                ProductID: productId,
                Rating: rating,
                // Do you need this now?
                CurrentRatingId: currentRating.attr('id')
            },
            cache: false,
            dataType: 'json',
            success: function (results) {
                // Update the current rating using the variable we stored above    
                currentRating.text(results.AverageRating + ' Stars');
            }
        });
    });
    

    我补充道 .eq(0) 为了确保我们只获取第一个元素(其ID属性将被发送到服务器)。

        2
  •  0
  •   cripox    14 年前

    喜欢 $("#" + currentRating.attr('id')).text(results.AverageRating + ' Stars');