![](/img/trans.png)
[英]Dynamic content from JSON only posts/repeats last key's data (should print all values)
[英]returned json data from table always repeats the one before last
我有一個div,它使用長輪詢來更新表數據,除了輸入新文本時,所有這些方法都起作用,插入的文本總是首先出現 , 然后才是我剛寫的內容。
因此,如果我打招呼,你好,再見,我將得到以下信息:
hi
hi
hello
hello
goodbye
相關的JS:
var timestamp = null;
function waitForMsg() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg']+'<br>'); // MD
}
timestamp = json['timestamp'];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('waitForMsg()', 1000);
}
});
}
update.php中的相關代碼段
$response = array();
while($row = mysqli_fetch_assoc($r)) {
$nou = $row['f1'];
$nru = $row['f2'];
$response['msg'] = $row['content'];
$response['timestamp'] = $row['time'];
}
echo json_encode($response);
為什么不只檢測最后輸入的內容並單獨顯示,而不重復輸入的先前數據?
編輯:我注意到了一些。
它似乎也吞沒了所輸入的內容,因此,如果表為空,並且我寫“ hi”,我會嗨,但是如果我寫“ hello”,我會再次“ hi”,然后如果我寫東西,然后否則我會收到“你好”(不是我剛剛寫的內容),依此類推。
替換$response['msg'] = $row['content'];
$response['msg'][] = $row['content'];
並更改下面的JS
代碼
if (json['msg']) {
$('.chat_contacts .inner_chat').append(json['msg'] + '<br>');
} // MD
同
if (json['msg'].length) {
var el = $('.chat_contacts .inner_chat');
$.each(json['msg'], function(i, v) {
el.append(v + '<br>'); //MD
});
}
並確保在sql query
您使用的是這樣的WHERE time > timestamp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.