0

我有以下代码:

function getChainDeals(chainID) {
    $('#loadingDiv1').show();
    var apiCode = * my unique api code * ;
    var imageURL;
    //Get relevant Image
    $.ajax({
        url: 'http://api.8coupons.com/v1/getchainstorelist?key=' + apiCode,
        dataType: 'jsonp',
        success: function (data) {

            $.each(data, function (key, value) {

                alert('key = ' + key);
                alert('chainid = ' + chainID);

                if (key === chainID - 1) {
                    alert('here');
                    imageURL = value.logoBig;
                    alert('imageURL = ' + imageURL);
                    return false;
                }
            });
            // hide the loading animation
            $('#loadingDiv1').hide();
        },
        statusCode: {
            404: function () {
                alert: ('There was a problem with the server');
            }
        }
    });
    alert(imageURL);
    alert(chainID);
}

然而,由于某种原因,AJAX呼叫被跳过,只有最后两个alerts正在处理。实际上,我之前在程序中使用了几乎相同的代码,效果很好……

谁能看到这里出了什么问题?

谢谢您的帮助。

4

1 回答 1

1

您应该将alerts 放在 ajax 回调中,因为 ajax 是异步的:

function getChainDeals(chainID) {
    $('#loadingDiv1').show();
    var apiCode = * my unique api code * ;
    var imageURL;
    //Get relevant Image
    $.ajax({
        url: 'http://api.8coupons.com/v1/getchainstorelist?key=' + apiCode,
        dataType: 'jsonp',
        success: function (data) {

            $.each(data, function (key, value) {

                alert('key = ' + key);
                alert('chainid = ' + chainID);

                if (key === chainID - 1) {
                    alert('here');
                    imageURL = value.logoBig;
                    alert('imageURL = ' + imageURL);
                    return false;
                }
            });
            // hide the loading animation
            $('#loadingDiv1').hide();

            alert(imageURL);
            alert(chainID);
        },
        statusCode: {
            404: function () {
                alert: ('There was a problem with the server');
            }
        }
    });
}
于 2013-11-06T14:19:12.360 回答