我有以下代码:
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
。我实际上在程序的早期使用了几乎完全相同的代码,但工作得很好......
谁能看到这里出了什么问题?
感谢您的帮助。
答案 0 :(得分:1)
你应该把alert
放在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');
}
}
});
}