将更新div的内容附加到另一个div

时间:2012-02-12 16:38:26

标签: jquery ajax

基本上,我有一个div(divNew),它使用ajax填充来自​​另一个页面(thread.php)的内容。不断刷新thread.php以从数据库中轮询数据。

每当divNew中有内容时,我希望divNew中的内容被附加到另一个div(chatContents)。为此我不断运行附加的javascript。 我面临的问题是只要thread.php没有刷新,就会发生追加。但是一旦发生,所有发生的追加都会被删除,并被最初的内容所取代。每次刷新thread.php时都会重复循环。

我不确定我是否正确解释这一点。我希望代码有所帮助。

    <script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<div id = "divNew" name = "divNew">
</div>
<h2>Greetings</h2>
<div class="container" id = "chatContents">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

<script>
 existingdiv1 = document.getElementById('divNew');


</script>
<script language="JavaScript">

setInterval("returnValue()", 1000); 
function returnValue()
{

 $.ajax({
            async: true,
            type: "GET",
            url: "thread.php",
            data: "html",
            success: function (html) {
                $("#divNew").html(html);   

            $('.inner').append([existingdiv1]);             
            }  
        });

}
</script>

任何帮助将不胜感激。谢谢:))

1 个答案:

答案 0 :(得分:0)

我会废除#newDiv的概念并做这样的事情:

您还导入了两次jQuery。我拿了一个。

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<h2>Greetings</h2>
<div class="container" id="chatContents">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

JS

setInterval("returnValue()", 1000); 
function returnValue()
{
 $.ajax({
            async: true,
            type: "GET",
            url: "thread.php",
            data: "html",
            success: function (html) {
                if(html)
                {
                   var newDiv = $('<div/>').html(html);   
                   $('#chatContents').append(newDiv);             
                }
            }  
        });
}
</script>

这将生成一个新的div,并在你从服务器返回时附加它。