此脚本使用 API 访问数据库中的信息,并为数据库中的随机人员显示“聚光灯”,其中包括他们的姓名、照片和简短的个人简介。
我正在尝试编写此脚本来检查图像是否存在。如果图像存在,则脚本应继续,但如果图像不存在(404 错误),则应重新滚动并再次检查。我在理解如何使用 ajax 的异步部分时遇到问题。
function checkImage(imgurl){
function headRequest(url){
return $.ajax({ //Makes a HEAD request for the image
url: url,
type: 'HEAD'
});
};
headRequest(imgurl)
.done(function(){
return true; //image exists
})
.fail(function(){
return false; //HEAD request returns 404
});
};
//if image does not exist or person.biography is undefined, reroll
while (!checkImage(imgsrc) || person.biography == undefined) {
//select random person
}
最佳答案
必须使用回调! (您无法从异步
调用返回)
function checkImage(imgurl, callback){
function headRequest(url){
return $.ajax({ //Makes a HEAD request for the image
url: url,
type: 'HEAD'
});
};
headRequest(imgurl)
.done(function(){
callback(true); //image exists
})
.fail(function(){
callback(false); //HEAD request returns 404
});
};
并调用该函数:
checkImage(imgsrc, function(exists) {
//exists is what you passed into the callback
if (exists) { //do stuff
} else {
//doesnt
}
});
关于javascript - 通过jquery ajax检查图像是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25750924/