javascript - 仅在完成时返回 ajax 调用的数据

标签 javascript ajax

我正在尝试将多个文件夹中的所有图像加载到一个数组中并将它们添加到我的页面

我正在使用下面的代码

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

代码可能在 ajax 调用实际返回之前访问 image_array 的问题。我研究过向 ajax 调用添加一个完成,但它没有用。

f1 如何调用 f2(f2 中有 ajax)并且仅当且仅当 f2 真正完成时才继续?


编辑:

仍然不确定我做错了什么

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

数据是:

(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)

最佳答案

你可以使用$.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
})

另见 How to print all the txt files inside a folder using java script

关于javascript - 仅在完成时返回 ajax 调用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361786/

相关文章:

javascript - 函数在运行内部操作之前返回值

php - DOM 操作 - 多种形式

javascript - 将对象内的列表发送到 Wcf 服务

jQuery Ajax文件上传: Required MultipartFile parameter 'file' is not present

javascript - DataTables ajax.reload() 丢失页面

javascript - 使用 jquery 从侧面滑动(没有 Jquery UI)

javascript - 在 Javascript 中使用授权 header

javascript - 在 IE 中使用 JavaScript 将 XML 加载到 DIV 时出现问题

javascript - 判断是否为asp :Placeholder is visible Jquery

javascript - 如何使用正则表达式匹配多个字符串?