2010-08-17 105 views
0

好的,所以我正在研究一个小图片库,它将使用AJAX加载一组图像。基本上它会加载一个'loading.gif'占位符图像,发出一个AJAX请求来生成缩略图。 PHP页面生成缩略图并发送图像已经生成的确认和路径。然后,我的onSuccess应该用实际的缩略图替换loading.gif。在完成所有请求之前,多个AJAX请求不会调用onSuccess

问题:这一切都很好,除非在所有未完成的请求完成之后,它不会开始放置缩略图。因此,不是让图像分开显示1秒或2秒,而是在具有20个缩略图的页面上生成,我等待20秒,然后在AJAX请求正在进行时,即使一些已准备好一段时间,然后开始显示缩略图。

这里是我的相关代码:

function getImageList() { 
//Get an XML list of all the images to be displayed. 
$.ajax({ 
url:"gallery.php", 
type: "POST", 
data:{mode: "getImageList"}, 
success: function(responseText){ 
    $(responseText).find('galImg').each(function(){ 

    //create the image divs and images, set properties and get values. 
    var imageBox = document.createElement('div'); 
    var imageElement = document.createElement('img'); 
    imageBox.setAttribute('class','imageBox'); 
    imgThumbPath = $(this).find('img_thumb').text(); 
    imgThumbReady = $(this).find('img_thumb_ready').text(); 
    imgPath = $(this).find('img_path').text(); 
    imageElement.setAttribute('id',imgPath); 
    imageBox.appendChild(imageElement); 
    $('#galleryContainer').append(imageBox); 

    //now load the src of the image 
    if (imgThumbReady=='no') { 
    imageElement.setAttribute('src',loadingImage); 
    $.ajax({ 
    url: "gallery.php", 
    type: "POST", 
    data: {mode: "generateThumbnail",imgPath:imgPath}, 
    success: function(response){ 
     if ($(response).find('message').text() == 'Sucess') { 
     imageElement.setAttribute('src',$(response).find('galImg').find('img_thumb').text()); 
     } else { 
     alert('Problem Loading Image - '+$(response).find('message').text()); 
     } 
     }, 
    datatype: "html" 
    }); 
    } else { 
    imageElement.setAttribute('src',imgThumbPath); 
    } 
    }); 
}, 
datatype:"html" 
}); 

} 

回答

1

我理解你的代码的方式,你这是一个Ajax请求生成所有你缩略图一次。你想要做的可能是做一些循环,使AJAX调用一个接一个地产生你的图像。为了避免有限的连接问题,您应该利用您的ajax请求的回调函数来启动下一个请求。

所以,你的代码逻辑会更喜欢这样的:

function loadImage(imagePath){ 
    $.ajax({ 
    url: "gallery.php", 
    type: "POST", 
    data: {mode: "generateThumbnail",imgPath:imgPath}, 
    success: function(response){ 
     // Your code to display this new thumnail goes here 
     imagePath(nextImage); 
    } 
}; 

此代码是未经测试和不完整的,但我认为这应该足以为你指明正确的方向。我认为这是获得你想要的效果的最简单/最安全的方法。让我知道它是否有帮助!

+0

你的意思是loadImage(nextImage)对不对? – letronje 2010-08-17 19:12:40

相关问题