Thứ Năm, 10 tháng 8, 2017

Ajax async

How do I update the returnHtml variable from within the anonymous success function?
function getPrice(productId, storeId) {
    var returnHtml = '';

    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: function(html){
            returnHtml = html;
        }
    });

    return returnHtml;
}
Answer:
That's the wrong approach. The first A in AJAX is Asynchronous. That function returns before the AJAX call returns (or at least it can). So this isn't an issue of scope. It's an issue of ordering. There are only two options:
  1. Make the AJAX call synchronous (not recommended) with the async: false option (default is true); or
  2. Change your way of thinking. Instead of returning HTML from the function you need to passin a callback to be called when the AJAX call succeeds.
As an example of (2):
function findPrice(productId, storeId, callback) {
    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: function(html) {
            callback(productId, storeId, html);
        }
    });
}

function receivePrice(productId, storeId, html) {
    alert("Product " + productId + " for storeId " + storeId + " received HTML " + html);
}

findPrice(23, 334, receive_price);

Không có nhận xét nào:

Đăng nhận xét