简体   繁体   中英

returning data for ajax call only when it is done

I am trying to load all images from several folders into an array and add them to my page

I am using the following code

function initialize()
{   
    //all images are stores in images/name_of_dir
    var folder = "images/";
    //we want to load images from several dirs. If in the future we want other dirs or more dirs 
    //we can update this array to point to the new dirs
    var possible_dirs = [ "cute", "disgusted", "neutral"];
    var image_array = [];
    for ( index = 0 ; index < possible_dirs.length; ++index) {
        image_array.push(getImagesFromFolder(folder +  possible_dirs[index] + "/"));
    }
//This loop will append images later. Need to fix this
//    for ( j = 0 ; j < image_array.length; ++j) {
//        $("body").append("<img src='" + image_array[j][0] + "'>");
//    }

}


function getImagesFromFolder(folder){
            var images_array = [];
            $.ajax({
            url : folder,
            success: function (data) {
                $(data).find("a").attr("href", function (i, val) {
                    if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                        images_array.push(folder + val);
                    } 
                return images_array;
                });
            }
        })
}

The problem that the code might access the image_array before the ajax call actually returned. I looked into adding a done to the ajax call, but it did not work.

How can f1 call f2 (f2 has ajax in it) and only continue if and only if f2 is truly done?


EDIT:

Still not sure what I am doing wrong

// Loads the images into arrays and starts introduction
function initialize()
{   
    //all images are stores in images/name_of_dir
    var folder = "images/";
    //we want to load images from several dirs. If in the future we want other dirs or more dirs 
    //we can update this array to point to the new dirs
    var possible_dirs = [ "cute", "disgusted", "neutral"];
    var images_array = [];
    $.when.apply($, possible_dirs.map(function(file) {
        return getImagesFromFolder(folder +  file + "/")
    }))
    .then(function(data) {
        // do stuff with `data`
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                images_array.push(folder + val);
            } 
        });
        console.log(images_array);
    }, function(jqxhr, textStatus, errorThrown) {
    // handle errors
    })
}

function getImagesFromFolder(folder) {
  // note `return` 
  return $.ajax({url : folder});
}

Data is:

(3) ["<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final/…235.jpg">1235.jpg</a>↵</ul>↵<hr>↵</body>↵</html>↵", "success", {…}]
0
:
"<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>↵<title>Directory listing for /images/cute/</title>↵<body>↵<h2>Directory listing for /images/cute/</h2>↵<hr>↵<ul>↵<li><a href=".DS_Store">.DS_Store</a>↵<li><a href="1223.jpg">1223.jpg</a>↵<li><a href="1235.jpg">1235.jpg</a>↵</ul>↵<hr>↵</body>↵</html>↵"
1
:
"success"
2
:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
length
:
3
__proto__
:
Array(0)

You can use $.when()

function getImagesFromFolder(folder) {
  // note `return` 
  return $.ajax(folder)
}

$.when.apply($, possible_dirs.map(function(file) {
  return getImagesFromFolder(folder +  file + "/")
}))
.then(function() {
  // do stuff with `data`
  var docs = $.makeArray(arguments).map(function(arr) { return arr.shift() });
  $.each(docs, function(key, doc) {
    console.log(doc); // parse HTML string
  });
}), function(jqxhr, textStatus, errorThrown) {
  // handle errors
})

See also How to print all the txt files inside a folder using java script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM