Ajax显示消息

时间:2013-06-22 14:26:51

标签: php javascript jquery ajax

拥有这段惊人的代码,它运行得非常好,但问题是我总是得到同样消息的新DIV,如何更改它以便它出现在同一个地方? msgsrv.php文件只是echo "Test Message";但它会从MySQL DB中提取数据。所以我得到的是Test Message,然后是下一行的Test Message,我想让NEW消息替换OLD消息。

<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>

1 个答案:

答案 0 :(得分:4)

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

替换

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

使用:

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