javascript - 在 json 中使用游标时无法读取未定义的属性 'length'

标签 javascript php jquery json

我有一个以 json 格式返回数据的 php 脚本:

[{"text_content":"gdgdsg","text_duration":"15"},{"text_content":"gdgdsg","text_duration":"15"},{"text_content":"gdgdsg","text_duration":"15"},

等]

我有一个 jquery 脚本来解析输入并在屏幕上显示文本:

var results;
var cursor = 0;

function myFunction () {
    $.getJSON('list2.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.
    $('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); });

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

    // Advance the cursor.
    cursor++;
}

但是当我运行它时出现以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined

在这一行中:

if(cursor == results.length){

这里可能出了什么问题?

编辑:

返回数据到json的php代码是:

if ($result = $mysqli->query("SELECT text_content, text_duration from user_text")) {

while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    }
    echo json_encode($myArray);
}

最佳答案

getJSON回调函数返回json数据。

var results= [];
    var cursor = 0;

function myFunction () {
    $.getJSON('list2.php', function(json) {
        results = json;
        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.
    $('#mydiv').hide('fast', function(){ $('#mydiv').html(results[cursor].text_content); $('#mydiv').show('fast'); });

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

    // Advance the cursor.
    cursor++;
}

关于javascript - 在 json 中使用游标时无法读取未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32976471/

相关文章:

javascript - facebook 未在 iframe 内加载

javascript - 端口: Could not establish connection. 接收端不存在

php - PHP shell_exec不适用于ssh

php - Codeigniter 3 上的 Mysqli 驱动程序不工作

javascript - jquery 不支持字符串变量

javascript - 根据滚动淡入或淡出

javascript - 如何格式化下拉列表中的日期?

javascript - 如何将 qtip2 工具提示移动到另一个元素?

javascript - Javascript 表达式 'a = a || function() {...}' 是什么意思?

php - 使用 DOMDocument 帮助解析 XML