当我的ajax请求返回成功时,我想做的是继续将div append 到#ajax_tweets
。当前发生的情况是每次 ajax 函数在计时器上运行并且 ajax 返回成功时,所需的最新 div 就会正确显示在屏幕上。然而,当它下次运行时,前一个 div 会被覆盖并且不会 append 。要么我 append 错误,要么我不确定……现在让我发疯了一段时间。
提前谢谢您。
我的代码:
$(document).ready(function() {
window.setInterval(ajax_test, 10000);
counter = 0;
function ajax_test() {
$(".tweets").html('Retrieving...');
$.ajax({
type: "POST",
url: "assets/ajax/get_latest_tweets.php",
data: "tid=" + id,
timeout: 20000,
success: function(msg) {
if (msg != "") {
add_to_tweet_feed( msg );
id++;
alert(id + msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$(".tweets").html('Timeout contacting server..');
}
});
}
function add_to_tweet_feed ( msg ) {
$("#ajax_tweets").append(msg);
}
});
服务器返回的代码:
<div id="'.$tid.'" class="t_feed">
<div class="calander right">
<div class="calander_month"><span>'.$row['pub_month'].'</span></div>
<div class="calander_day"><span>'.$row['pub_day'].'</span> </div>
</div>
<span class="ajax_tweet bold">'.$row['source'].'</span>
<p>'.$tweet.'</p>
</div><div class="clear_both></div>
前端代码:
<div id="ajax_tweets" class="tweets">
</div>
最佳答案
代码中的这一行实际上清除了整个容器,这就是为什么你只有最后一个容器:
$(".tweets").html('Retrieving...');
一种解决方案可能是使您的标记如下所示:
<div id="ajax_tweets" class="tweets">
<div id="ajax_message"></div>
</div>
...并更改代码以更新该元素并在其前面插入新推文:
$(document).ready(function() {
window.setInterval(ajax_test, 10000);
counter = 0;
var $message = $("#ajax_message");
function ajax_test() {
$message.html('Retrieving...');
$.ajax({
type: "POST",
url: "assets/ajax/get_latest_tweets.php",
data: "tid=" + id,
timeout: 20000,
success: function(msg) {
$message.html('');
if (msg != "") {
add_to_tweet_feed( msg );
id++;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$message.html('Timeout contacting server..');
}
});
}
function add_to_tweet_feed ( msg ) {
$(msg).insertBefore($message);
}
});
编辑:修复了上述代码中的错误(insertBefore()
的错误使用)。另外,如果您担心请求返回的顺序,您可以添加占位符并在成功时替换它们或在失败时删除它们:
$(document).ready(function() {
window.setInterval(ajax_test, 10000);
counter = 0;
var $message = $("#ajax_message");
function ajax_test() {
$message.html('Retrieving...');
var $placeholder = $('<div></div>').insertBefore($message).hide();
$.ajax({
type: "POST",
url: "assets/ajax/get_latest_tweets.php",
data: "tid=" + id,
timeout: 20000,
success: function(msg) {
$message.html('');
if (msg != "") {
add_to_tweet_feed(msg, $placeholder);
id++;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$placeholder.remove();
$message.html('Timeout contacting server..');
}
});
}
function add_to_tweet_feed (msg, $placeholder) {
$placeholder.show().replaceWith(msg);
}
});
关于从函数运行时,Jquery 追加不按顺序添加 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6101411/