Ajax显示消息

Ajax Displaying Message

本文关键字:消息 显示 Ajax      更新时间:2023-09-26

有一段令人惊叹的代码,它运行得很好,但问题是我总是得到带有相同消息的新div,我如何更改它,使它出现在相同的位置?msgsrv.php文件只是一个echo "Test Message";,但它将从MySQL数据库中提取数据。所以我得到的是测试消息,然后是下一行的测试消息,我想用新消息代替旧消息。

<html>
<head>
    <title>Auction</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>
    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }
    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",
            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */
            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };
    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            Last Bid is:
        </div>
    </div>
</body>
</html>

正如它所说,"append"将把内容附加到元素中,而.html()将更改元素的整个内部html并替换为您设置的内容。

更换

$("#messages").append(
        "<div class='msg "+ type +"'>"+ msg +"</div>"
    );

带有:

$("#messages").html(
        "<div class='msg "+ type +"'>"+ msg +"</div>"
    );