我从一个页面和一个php服务器端页面(server.php)发送了许多动态post ID并用这些id进行查询以找出新增数据在MySQL中。JS只返回隐藏未定义值后数组中第一个id的值
如果没有发现在MySQL任何新添加的数据,它返回一个undefined
值。所以我加了这个if (msg.id !== undefined && msg.detail !== undefined && msg.name !== undefined) { //do here }
来隐藏未定义的。
但是,在添加上面的行后,我的脚本隐藏undefined
值很好,但只返回第一个CID的新增值。
这意味着如果CID向php发送了id(100,101,102,103等),它只返回100个id的新增值并追加它。
请问哪里有问题?
N.B.如果没有上面的行,它将返回所有CID的值,但如果没有找到新数据,还会返回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){
if (msg.id !== undefined && msg.detail !== undefined && msg.name !== undefined) {
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='newkochi'>"+ msg.name +"</div><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
}
});
}
function waitForRep(){
$.ajax({
type: "GET",
url: "server.php",
cache: false,
data: {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在JavaScript
while (true) {
if($_GET['CID']){ //cid got all dynamic post id as: 1,2,3,4 etc.
foreach($_GET['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=".$_GET['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
} //while close
} //foreach close
$name .='<p class="name">'.$username.' Says:</p>';
$detail .=''.$description.'';
$data['name'] = $name;
$data['detail'] = $detail;
// do others something more like as above
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} //request close
sleep(5);
} //while close
您的SQL字符串LIMIT 1,所以查询只获取一行。并且你应该在查询字符串中转义REQUEST参数以避免SQL注入 – 2015-03-13 09:51:14
Ok删除REQUEST,但是LIMIT 1对此没有任何影响,但也删除它并且不起作用。 – koc 2015-03-13 10:13:09