javascript - 如何在我的网页上一个一个地打印来自 json 的 key ?

标签 javascript php jquery mysql json

我写了下面的 php 代码:

$q3 = $conn3->prepare("SELECT c.text as key1, c.timeframe as key2, p.date as key3 FROM table1 c, table2 p WHERE c.id = p.c_id");
$q3->execute();

if ($q3->rowCount() > 0)
{
    $check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
    $arr = array();
    foreach ($check3 as $row) {
        $arr[] = $row;
    }
    echo json_encode(array('result'=>$arr)); 
}

它以一种形式返回我的 json 字符串:

{
    "result": [{
        "key1": "aa",
        "key2": "15",
        "key3": "2015-04-12 18:50:00"
    }, {
        "key1": "bb",
        "key2": "30",
        "key3": "2015-05-09 11:26:38"
    }, {
        "key1": "cc",
        "key2": "45",
        "key3": "2015-04-12 18:50:20"
    },

等 现在我希望将此结果打印在其他网页上,所以首先我在其中包含以下脚本:

<script type="text/javascript">
    function myFunction () {
        $.getJSON('list.php', function(json) {
            jQuery.each( json.result, function( i, subresult ) {
                console.log(subresult);
            });
        });
    }

    var interval = setInterval(function () { 
        myFunction(); 
    }, 60000);
</script>

运行该网页后,我会在控制台中看到结果 - 每分钟我都会调用 getJSON 方法并在控制台中打印返回的结果。所以我基本上在控制台中看到了 json 字符串。但是,我想一个一个地打印网页上的每个字符串 - 在同一个 div 中,例如淡入/淡出效果。对于上面的示例,我希望看到 "aa" 15 秒,然后是 "bb" 30 秒,"cc" 45 秒秒(持续时间存储为 key2 值)。

我在上面添加了间隔,因为一分钟后我想从 mysql 数据库中获取另一个数据并打印它而不是旧数据,等等。 你能帮我吗? 谢谢!

最佳答案

这里有一个解决方案:

<script type="text/javascript">
    var results;
    var cursor = 0;

    function myFunction () {
        $.getJSON('list.php', function(json) {
            results = json.result;
            cursor = 0;

            // Now start printing
            printNext();
        });
    }

    function printNext(){
        if(cursor == results.length){
            // Reset the cursor back to the beginning.
            cursor = 0;
        }

        // Print the key1 in the div.
        $('#divTarget').html(results[cursor].key1);

        // Set a delay for the current item to stay
        // Delay is key2 * 1000 seconds
        setTimeout(function(){
            printNext();
        }, results[cursor].key2 * 1000);

        // Advance the cursor.
        cursor++;
    }

    var interval = setInterval(function () { 
        myFunction(); 
    }, 60000);
</script>

关于javascript - 如何在我的网页上一个一个地打印来自 json 的 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30454963/

相关文章:

javascript - reCAPTCHA v3 - 错误 : No reCAPTCHA clients exist

javascript - addClass 可以工作但不能removeClass

javascript - html - 如果鼠标点击几秒钟触发事件

jquery - 具有负边距的 SlideToggle 无法按预期工作

javascript - document.body.appendChild(scriptElement) 后函数不可用

javascript - 半屏侧边栏修正

javascript - 如何使用 jQuery 计算和显示 font-awesome 的评级

javascript - PHP 通过电子邮件将选定的变量发送给用户

php - 使用带密码的 Redis 和 Laravel

php - 我的 Facebook 登录对话框在 IE 中没有关闭