给定一个图像列表,如何让它们在JavaScript / HTML中按顺序显示?

时间:2016-08-08 14:12:16

标签: javascript html ajax flask

我正在构建一个Flask应用程序,我的网页按特定顺序接收图像列表(及其元数据),以网格结构显示,类似于服装网站显示服装图像的方式。问题是,目前,图像按照最快加载的顺序出现,因此,每次重新加载页面时,我都会得到不同的图像顺序。

get_similar_images函数是我收到图像列表的地方,函数populateImages是我实际将此图像及其元数据附加到我的html的地方。

基本上,我不希望for中的get_similar_images循环移动到下一次迭代,直到前一个图像完全加载。感谢有关如何实现这一点的任何帮助!

function populateImages(imageUrl, retailer, name, price, retailerUrl) {
    var block = document.createElement("div");
    block.className = 'image-block';

    var img = document.createElement("img");
    img.src = imageUrl;
    img.className = 'clickable-image';

    // link to external site
    var clickableLink = document.createElement("a");
    clickableLink.href = retailerUrl;
    clickableLink.target = "_blank";
    clickableLink.appendChild(img);

    // add metadata        
    var description = document.createElement("div");

    var retailerName = document.createElement("p");
    retailerName.className = 'description-text';
    var retailerNameText = document.createTextNode(retailer);
    retailerName.appendChild(retailerNameText);
    description.appendChild(retailerName);

    var productName = document.createElement("p");
    productName.className = 'description-text';
    var productNameText = document.createTextNode(name);
    productName.appendChild(productNameText);
    description.appendChild(productName);

    var productPrice = document.createElement("p");
    productPrice.className = 'description-text';
    var productPriceText = document.createTextNode('$'+price);
    productPrice.appendChild(productPriceText);
    description.appendChild(productPrice);

    // resize image
    var actualH;
    var actualW;
    var newH;
    var newW;
    img.onload = function() {
        actualW = this.width;
        actualH = this.height;
        var newSize = scaleSize(300, 300, actualW, actualH);
        this.width = newSize[0];
        this.height = newSize[1];
        block.appendChild(clickableLink);
        block.appendChild(description);
        document.getElementById('imageDiv').appendChild(block);
    }; 
}

function get_similar_images(image_name) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/get_similar",
        dataType: "json",
        async: true,
        data: JSON.stringify({name: image_name}),
        success: function(data) {
            var image_list = data.images;
            var category = data.category;
            var retailers = data.retailers;
            var names = data.names;
            var prices = data.prices;
            var urls = data.urls;
            for (var i=0; i<image_list.length; i++) {
                var url = "static/products/"+category+"/"+image_list[i];
                populateImages(url, retailers[i], names[i], prices[i], 
                    urls[i])
            }
        },
        error: function(xhr, status, error) {
        }
    });
}

0 个答案:

没有答案