0

我有 3 个从 Web 服务获得响应的 ajax 请求,然后我想使用这些响应并将其注入到 document.load 中。当我尝试注入 html 时,请注意更改。我想我需要某种类型的回调,但我不知道该怎么做。谢谢,

$(document).ready(function prepareDocument() {
    var pageId = getPageId();
    var ratingHtml = '<div id="rating" class="rating" data-role="rating" data-param-vote="on" data-param-rating="3" onclick="confrimRatingInsert()"></div><p>#ofRatings</p>';
    canEditRating(pageId, function (data) {
        if (data.msg == null) {
            canEdit = data.result;
            if (canEdit == false) {
                ratingHtml = ratingHtml.replace('data-param-vote="on"', "");
            }
        }
        else {
            displayDialogBox("Error", data.msg);
        }
    });
    getAverageRating(pageId,function(data) {
        if (data.msg == null) {
            averageRating = data.result;
            ratingHtml = ratingHtml.replace('data-param-rating="3"', 'data-param-rating="' + averageRating + '"');
        }
        else {
            displayDialogBox("Error",data.msg);
        }      
    });
    getNumberOfRatings(pageId, function (data) {
        if (data.msg == null) {
            numberOfRatings = data.result;
            ratingHtml = ratingHtml.replace('#ofRatings', "( " + numberOfRatings + " sRatings)");
        }
        else {
            displayDialogBox("Error", data.msg);
        }
    });
    alert(ratingHtml);
});
function canEditRating(pageId,fn) {
    $.ajax({
        url: "../services/rating.ashx?action=canEditRating&pageId=" + pageId,
        dataType: "json",
        type: "GET",
        data: {},    
        success: function (data) {
            fn(data);
        },
        error: function (err) {
            displayDialogBox("Error", err.toString());
        }
    });
}
function getAverageRating(pageId, fn) {
    $.ajax({
        url: "../services/rating.ashx?action=getAverageRating&pageId=" + pageId,
        dataType: "json",
        type: "GET",
        data: {},
        success: function (data) {
            fn(data);
        },
        error: function (err) {
            displayDialogBox("Error", err.toString());
        }
    });
}
function getNumberOfRatings(pageId, fn) {
    $.ajax({
        url: "../services/rating.ashx?action=getNumberOfRatings&pageId=" + pageId,
        dataType: "json",
        type: "GET",
        data: {},
        success: function (data) {
            fn(data);
        },
        error: function (err) {
            displayDialogBox("Error", err.toString());
        }
    });
}
4

1 回答 1

0

Ajax 是异步的,当你调用时alert(ratingHtml);,响应还没有到达。因此,此时没有任何变化。但是您为您的 3 个 ajax 调用提供回调,这 3 个回调将在稍后调用并更改 ratingHtml。换句话说,在您的情况下,ratingHtml更新,但不会在您调用 alert(ratingHtml); 时更新。

于 2013-06-13T12:58:13.033 回答