gpt4 book ai didi

javascript - 如何停止 json_encode 返回未定义

转载 作者:行者123 更新时间:2023-12-03 10:35:23 27 4
gpt4 key购买 nike

我从一个页面发送了许多动态帖子 ID,并且 PHP 服务器端页面(server.php)使用这些 id 进行查询以查找 mysql 中的新添加的数据

如果在 mysql 中未找到任何新添加的数据,则返回一个未定义值。因此,根据我的脚本,它会每隔一段时间一个又一个地附加一个 undefined

如何停止这个未定义的值?

我的 JavaScript:

var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});

function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
});
}

function waitForRep(){
$.ajax({
type: "GET",
url: "server.php",
cache: false,
contentType: "application/json; charset=utf-8",
data: {
// this way array containing all ID's can be sent:
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}

$(document).ready(function(){
waitForRep();
});

服务器.php

while (true) {
if($_REQUEST['CID']){ //cid got all dynamic post id as: 1,2,3,4 etc.
foreach($_REQUEST['CID'] as $key => $value){

$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$data = array();
while($rows = mysqli_fetch_assoc($res)){

$data[]=$rows;

$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['username'] = $rows['username'];
$data['description'] = $rows['description'];
$data['date'] = $rows['date'];
//etc. all
$id = $rows['id'];
$qazi_id = $rows['qazi_id'];
$username = $rows['username'];
$description = $rows['description'];
//etc. all
} //foreach close
} //foreach close

if ($description=="") {$detail .= '';}
else {$detail .=''.$description.'';}
$data['detail'] = $detail;
// do somethig

if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}

} //request close
sleep(5);
} //while close

最佳答案

编辑您的 addrep 函数,使其在未定义时不插入:

function addrep(type, msg){
CID.forEach(function(id){
if(msg.detail != "undefined") {
$("#newreply"+id).append("+ msg.detail +");
}
});
}

或者如果未定义则中断它:

function addrep(type, msg){
CID.forEach(function(id){
if(msg.detail == "undefined")
break;
$("#newreply"+id).append("+ msg.detail +");
});
}

关于javascript - 如何停止 json_encode 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29010995/

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