Checking if file exists using $.ajax() problem
I am having a problem checking if a file exists using $.ajax(). I am looping through a json file with $.each and I want to see if the specified staff member has an image, and if not use the no_photo.jpg image. I keep getting the no_photo.jp开发者_Go百科g image even though there is the staff member's image in the directory.
Here is the entire $.getJSON() call.
$.getJSON('staff.json', function(data) {
var last_check;
var image_url = "no_photo";
$.each(data.employees, function(i,employee){
if ((i+1)%4==0) {last_check = " last";} else {last_check = "";}
$.ajax({
url:'/images/staff/' + employee.first_name.toLowerCase() + employee.last_name.toLowerCase() + '.jpg',
type:'HEAD',
error:
function(){
image_url = "no_photo";
},
success:
function(){
image_url = employee.first_name.toLowerCase() + employee.last_name.toLowerCase();
}
});
$("div.staff-members").append('<a href="#" title="' + employee.first_name + ' ' + employee.last_name + ', ' + employee.title + '" rel="' + employee.location + '" class="' + employee.category + last_check + '"><img src="/images/staff/' + image_url + '.jpg"><span class="' + employee.category + '"></span></a>');
});
});
I'd strongly recommend not to use jQuerys .ajax()
(or any other XHR) method for that purpose. Use Javascripts
Image object instead.
var testimg = new Image();
testimg.onload = function(){
if(this.width > 0)
image_url = this.src;
else
image_url = "no_photo";
$("div.staff-members").append('<a href="#" title="' + employee.first_name + ' ' + employee.last_name + ', ' + employee.title + '" rel="' + employee.location + '" class="' + employee.category + last_check + '"><img src="/images/staff/' + image_url + '.jpg"><span class="' + employee.category + '"></span></a>');
};
testimg.onerror = function(){
image_url = "no_photo";
$("div.staff-members").append('<a href="#" title="' + employee.first_name + ' ' + employee.last_name + ', ' + employee.title + '" rel="' + employee.location + '" class="' + employee.category + last_check + '"><img src="/images/staff/' + image_url + '.jpg"><span class="' + employee.category + '"></span></a>');
};
testimg.src = '/images/staff/' + employee.first_name.toLowerCase() + employee.last_name.toLowerCase() + '.jpg';
This has less overhead than an Ajax request
.
update
moved the .src =
instruction to the bottom (msie requires this, credits to Nick Craver)
Since this approach uses asynchronous callbacks (as does .ajax()
), you need to call your .append()
within the event handlers.
精彩评论