如何创建我们从 PHP 收到的尽可能多的 dynamicEl

How to to create as much dynamicEl, as we received from PHP

主页上有图库,单击图像需要打开 lightGallery 幻灯片,其中包含在 ftp 目录中找到的图像,以及在主页上单击的图库名称。

PHP 查找图像并计数:

<?php
header("Content-Type: application/json");

$dirname = $_POST["galleryName"];

$imgGallery = glob("../gallery/" . $dirname . "/".$dirname."_*.*");
$thumbGallery = glob("../gallery/" . $dirname . "/thumb_*.*");

$countImages = count($imgGallery);

echo json_encode(array("imgNormal" => $imgGallery, "imgThumb" => $thumbGallery, "imgCount" => $countImages));
?>

JS:

$('.info').click(function() {
    var galleryName = $(this).closest('.imgGallery').find('img.img-thumbnail').attr('name');
    $.ajax({
        url: "gallery/imgFinder.php",
        dataType: "json",
        type: "post",
        data: {
            galleryName: galleryName
        },
        success: function(xhr) {
            if (xhr.imgCount != 0) {
                console.log(xhr.imgNormal);
                console.log(xhr.imgThumb);
                console.log(xhr.imgCount);
                for (var i = 1; i <= xhr.imgCount; i++) {
                    $(this).lightGallery({
                        dynamic: true,
                        dynamicEl: [{ //We need to create as much as we received w "xhr.imgCount"
                                        "src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
                                        "thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
                        }]
                    })
                    return;
                }
            } else {
                console.log('Gallery \'' + galleryName + '\' has no images');
                return;
            }
        },
        error: function(xhr) {
            console.error("Some error found");
        }
    });
});

我们需要使用 image/thumb 变量创建尽可能多的 dynamicEl,因为我们收到 xhr.imgCount

要得到这样的东西:

dynamicEl: [{
    "src": '...',
    'thumb': '...'
}, {
    'src': '...',
    'thumb': '...'
}, {
    'src': '...',
    'thumb': '...'
}, {
    'src': '...',
    'thumb': '...'
}]

在您的 JS 代码中,您需要进行如下更新:

if (xhr.imgCount != 0) {
        console.log(xhr.imgNormal);
        console.log(xhr.imgThumb);
        console.log(xhr.imgCount);
        var dynamicEls = [];
        for (var i = 0; i <= xhr.imgCount; i++) {

              dynamicEls[i] = { 
                    "src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
                    "thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
                };
        }
        dynamicEls.pop(); //For remove unrealized last url/data
        $(this).lightGallery({
           dynamic: true,
           dynamicEl: dynamicEls
        });
    }

因此,我正在使用临时变量 dynamicEls 并在循环后将其填充到正确的位置。