Javascript 在完成所有请求之前,多个AJAX请求不会调用onSuccess

Javascript 在完成所有请求之前,多个AJAX请求不会调用onSuccess,javascript,ajax,jquery,Javascript,Ajax,Jquery,好的,我正在开发一个小照片库,它将使用AJAX加载一组图像。基本上,它将加载一个“loading.gif”占位符图像,发出AJAX请求以生成缩略图图像。PHP页面生成缩略图,并发送一条确认消息,确认已生成图像及其路径。然后,我的onSuccess应该将loading.gif替换为实际的缩略图 问题是:这一切都很好,只是在完成所有未完成的请求之前,它不会开始放入缩略图。因此,在一个需要生成20个缩略图的页面上,我没有让图像相隔1秒或2秒显示,而是在AJAX请求进行时等待20秒,然后开始显示缩略图,

好的,我正在开发一个小照片库,它将使用AJAX加载一组图像。基本上,它将加载一个“loading.gif”占位符图像,发出AJAX请求以生成缩略图图像。PHP页面生成缩略图,并发送一条确认消息,确认已生成图像及其路径。然后,我的onSuccess应该将loading.gif替换为实际的缩略图

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

这是我的相关代码:

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"  
});  

}

按照我对代码的理解,您正在发出一个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);
    }
};
此代码未经测试且不完整,但我认为它应该足以为您指明正确的方向。我认为这是获得你想要的效果的最简单/最安全的方法。如果有帮助,请告诉我