【问题标题】:MySQL/jQuery: fetch table results, pass into a jQuery array, show only 6 at a time and rotate results at randomMySQL/jQuery:获取表结果,传入一个 jQuery 数组,一次只显示 6 个并随机旋转结果
【发布时间】:2019-03-20 13:09:53
【问题描述】:

我在一个 MySQL 表中有 12 个用户。他们的 ID 可以是任何东西,因为他们的 ID 是随机生成的(但这是另一回事)。

为方便起见,我们假设 ID 是 1-12。

我还将用户个人资料照片存储在一个目录中:

目录 = data/profiles/users/profile_img/{USER_ID}/main.jpg

我正在运行 MySQL 查询(工作正常)来获取所有 12 个用户 user_ids。然后,我将这些 ID 传递到一个 jquery 数组中,并将它们放入一个函数,该函数通过更改图像类 src 属性来随机化这些在页面上显示为图像的顺序 - 这一点是使用 jQuery 完成的。

请注意,我使用的是随机函数,因为我只希望在任何给定时间以随机顺序显示 12 个结果中的 6 个。

这有效,图像以随机顺序显示,并且每 5 秒旋转/更改一次。

但是,围绕我的图像的是一个 href 类“premium_component_link”。我想将每个个人资料图片链接到其相应的用户个人资料页面。

我尝试过这样使用这个父级来做到这一点:

$(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + displayImage()) 

我遇到的问题是 displayImage() 正在重新生成一个单独的随机 user_id,因此当用户单击它时,正在显示的图像与配置文件链接不相关。

有点跑题了,但最终我还想从 user_id 匹配的表中获取用户名和位置,并将它们放在我的类之间“h3 class="mt-4" - 但我没有知道我将如何做到这一点,并且认为我不应该在走路之前跑步。

在每次函数出现期间,我是否可以将一个 displayImage() 实例一起传递给这两个属性 href 和 src?

代码:

<?php $result = $conn->query("SELECT  * FROM user_data WHERE advert_type = 'Deluxe'");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { 
$p_id = $row['user_id'];

$new_array[$p_id] = $row['user_id'];


echo '<script>';
echo 'var imagesArray = ' . json_encode($new_array) . ';';
echo '</script>';            
?>    


<script>

var usedImages = {};
var usedImagesCount = 0;

var imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]

function displayImage() {
    var index = Math.floor(Math.random() * (imageIndexes.length));
    var num = imageIndexes[index]

    var result = imagesArray[num];
    imageIndexes.splice(index, 1)

    if (imageIndexes.length === 0) {
        imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]
    }
    return result
}


function changeImagesSrc() {

    $(".premium_ad_img").each(function () {
        $(this).attr('src','data/profiles/users/profile_img/' + displayImage()) + '/main.jpg')       
        $(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + displayImage())
    }) //End Change IMage


} //End Function Change

$(document).ready(function () {

    changeImagesSrc()
    setInterval(function() {
        changeImagesSrc()
    }, 5000);
})

</script>

<? } } ?>



<?php 
//Echo out results
echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';

echo '<div class="premium_component"><a href="" class="premium_component_link">';
echo '<img class="premium_ad_img" src="" height="auto" width="auto" />';
echo '<div class=" choose-grid"><h3 class="mt-4">Mark London</h3><p class="">25, London UK</p></div></a></div>';



?>

【问题讨论】:

    标签: javascript php jquery mysql


    【解决方案1】:

    对于您的 javascript 标记,您真的只需要一个 shuffle 函数和一个包罗万象的 changeComponent 函数,它可以完成每个间隔心跳的所有工作。此外,您会注意到 jQuery 有一个更有用的 each() 函数版本,它提供当前元素的索引:

    <?php $result = $conn->query("SELECT  * FROM user_data WHERE advert_type = 'Deluxe'");
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) { 
            $p_id = $row['user_id'];
            $new_array[] = $p_id;
        }
    }
    
    echo '<script>';
    echo 'var imagesArray = ' . json_encode($new_array) . ';';
    echo '</script>';            
    ?> 
    
    <script>
    //Good shuffle algorithm: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
        function shuffle(array) {
            var currentIndex = array.length, temporaryValue, randomIndex;
    
            // While there remain elements to shuffle...
            while (0 !== currentIndex) {
    
                // Pick a remaining element...
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;
    
                // And swap it with the current element.
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;
            }
    
            return array;
        }
    
        function changeComponent() {
            // store image query in a variable
            var $allImages = $(".premium_ad_img");
            // take X random IDs by shuffling the list and taking the first X
            // (slice total dynamically, in case you ever need more or less than exactly 6)
            var randomIDs = shuffle(imagesArray).slice(0, $allImages.length);
    
            // iterate over each image, using the index of the iteration.
            $allImages.each(function (idx) {
                $(this).attr('src', 'data/profiles/users/profile_img/' + randomIDs[idx] + '/main.jpg');
                $(this).parent(".premium_component_link").attr('href', 'profile.php?p_id=' + randomIDs[idx]);
            });
        }
        $(document).ready(function () {
    
            changeComponent();
            setInterval(function() {
                changeComponent();
            }, 5000);
        })
    </script>
    

    【讨论】:

    • 谢谢,这似乎工作得更顺畅了。然而,我向我们的朋友@Nawed Khan 指出了同样的问题。并非我的 mysql 表中的所有 user_id 都是 1-12。这只是一个例子。我的 user_ids 是 8 位整数,例如 12345678 或 0134546。它们不会是 1-12。在我测试代码的那一刻,它适用于 user_ids 1-12,但不适用于 user_id 44456784。我认为这与 imageIndexes 有关。有没有办法改变它以适应这个要求?谢谢
    • @M.Obren 我明白了;我已经更正了我的答案以随机播放您的实际 imageArray。但是,要使其与您的 PHP 一起使用,您必须将其更改为:$new_array[$p_id] = $row['user_id']; 至此:$new_array[] = $p_id;,这将不断地将您的 $p_id 元素附加到数组的末尾。
    【解决方案2】:

    您可以将 displayImage() 的结果存储到一个变量中,并根据需要多次使用它,而无需再次调用该函数。那是最基本的编程概念......就像爬行(用你的话)。

       function changeImagesSrc() {
    
                $(".premium_ad_img").each(function () {
                   var display = displayImage();
                   $(this).attr('src','data/profiles/users/profile_img/' + display + '/main.jpg');       
                   $(this).parent(".premium_component_link").attr('href','profile.php?p_id=' + display);
                }); 
        }
    

    您的数组索引与用户 ID 相同,但在您的 javascript 中,您从 1 到 number_of_images 循环。您需要将数组索引为 0 到 number_of_records... 执行以下操作:

    替换这个:

    while($row = $result->fetch_assoc()) { 
    $p_id = $row['user_id'];
    
    $new_array[$p_id] = $row['user_id'];
    

    用这个:

    $i = 0;
    while($row = $result->fetch_assoc()) {    
       $new_array[$i] = $row['user_id'];
       $i++;
    }
    

    【讨论】:

    • 谢谢你。但是,我最初确实尝试将其存储为变量......但由于某种原因,jquery 完全停止运行。不幸的是,当我尝试使用您的代码时,同样的问题
    • 这似乎正在工作。虽然说我有一个 user_id 为 100 的用户,但这不会显示。那是因为变量中的 ImageIndexes 设置为 0 - 11 吗?如果是这样,有没有办法可以改进它以适应任何整数值 0-1000 或更高?事实上,表中总共只有 12 个用户,但他们的 user_id 并不总是 1-12。有什么方法可以提供额外的支持吗?
    • 这是因为您的数组索引与用户 ID 相同,但在您的 javascript 中,您从 1 到 number_of_images 循环。您需要将数组索引为 0 到 number_of_records。我已经更新了代码以包含它。
    • 我很困惑。我如何实现这段代码?我要删除 Var usedImages Count 吗?如果我这样做,那么 mysql 结果在哪里传递到 javascript?
    • @Newad Khan 请查看我在您的答案中附加的代码编辑。请检查我的实施是否正确?
    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多