我从一个页面发送了许多动态post id,并且php服务器端页面(server.php)使用这些id进行查询,以在mysql中找出新添加的数据。
如果在mysql中未找到任何新添加的数据,它将返回undefined
值。因此,根据我的脚本,它会以一个时间间隔逐个追加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();
});
server.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
答案 0 :(得分:1)
编辑你的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 +");
});
}