weixin_33734785 2015-10-20 05:45 采纳率: 0%
浏览 17

从ajax获取所有图像

function checkallfolder(){
  var thumbnailbox = $('#thumbnailbox');
  var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];
  for (var c = 0; c < foldertype.length; c++ ){
    var folder = 'Img/dfolder/'+foldertype[c];
    $.ajax({
      type : "POST",
      url: "data.php",
      contentType:"application/x-www-form-urlencoded",
      dataType: "json",
      data: "folder="+folder,
      success: function(d) {
        var temp = '';
        thumbnailbox.html('');
        for (var obj in d){
          if (d.hasOwnProperty(obj) && d[obj].hasOwnProperty('src') && d[obj].src !== ''){
            var objname = d[obj].name;
            temp += "<div><img name="+d[obj].name+" class='icon' src="+d[obj].src+"></div>";
            console.log(d[obj].src);
          }
        }
        thumbnailbox.html(temp);
      }
    });
  }
}

my intention is to use ajax check all folder inside image , so i loop it with "for" and i checked the con log it do load 7 times and all object are calling out but then i try to output them as "img" with "src". i only get the last img , only folder7/img7 had be show up. what is wrong with my code? all the "src" had been call out , it should be having all image. can anyone help me take a look ?

  • 写回答

2条回答 默认 最新

  • weixin_33682790 2015-10-20 05:50
    关注

    This is a classic case for using closure.

    Problem:

    Variables in JavaScript have function-level scope. Since you are using AJAX (Asynchronous call) inside the loop, your loop will execute no matter the response of the AJAX call. So, by the time AJAX is fired, your loop would have completed and each time your local variable is overwritten and hence, your c always points to value set in the last iteration of the loop.

    Make foldertype a global variable. Move it outside your function:

     var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];
    

    and then inside your checkallfolder() do this:

    ...
    for (var c = 0; c < foldertype.length; c++ ){
    var folder = getImageSrc(c);
    ...
    

    and the add getImageSrc like this:

    function getImageSrc(c){
       return 'Img/dfolder/'+foldertype[c];
    }
    

    So, in all your code looks like this:

    var foldertype = ["img1", "img2", "img3", "img4", "img5", "img6", "img7"];
    
    
    function checkallfolder(){
          var thumbnailbox = $('#thumbnailbox');
          for (var c = 0; c < foldertype.length; c++ ){
              var folder = getImageSrc(c);
              $.ajax({
                    ...ajax code here...
              });
           }
    }
    
    function getImageSrc(c){
       return 'Img/dfolder/'+foldertype[c];
    }
    
    评论

报告相同问题?