gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:13:52 25 4
gpt4 key购买 nike

我有一个以 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com