阿贾克斯:添加全新< DIV>从JSON与jQueryDIV、lt、阿贾克斯、jQuery

2023-09-10 16:46:43 作者:呐誰╮我説的①辈子疼n1

在一个页面我有这样的HTML code:

In a page I have this HTML code:

 
<div id="content">
    <div class="container">
        <div class="author">@Francesc</div>
        <div class="message">Hey World!</div>
        <div class="time">13/06/2010 11:53 GMT</div>
    </div>
    <div class="container">
        <div class="author">@SomeOtherUser</div>
        <div class="message">Bye World!</div>
        <div class="time">13/06/2010 14:53 GMT</div>
    </div>
    <div class="container">
        <div class="author">@Me</div>
        <div class="message">Hey World!</div>
        <div class="time">13/06/2010 18:53 GMT</div>
    </div>
</div>

我想问一下,如何得到一个JSON文件,从具有更近的邮件服务器,并把它们顶端,我的意思是上面的第一个&LT; D​​IV CLASS =容器&GT;

I want to ask, how to get a JSON file, from the server that has more recent messages and put them to the top, I mean above the first <div class="container">.

另一个问题,有可能通过与GET submiting当向服务器发出请求,最后一次更新的时间?我该怎么办呢? 谢谢你。

Another question, it's possible to pass with GET when submiting the request to the server, the time of last update? How can I do it? Thanks.

推荐答案

我不知道你的服务器提供了新的数据。

I don't know how your server is serving up the new data.

鉴于名为 new_data.json 在相同的目录页面静态文本文件,你可以做以下的AJAX请求。

Given a static text file called new_data.json in the same directory as your page, you could make the following ajax request.

(如果你从文件系统服务的页面,一些浏览器可能会给你一个小麻烦。Safari浏览器应该工作。)

(If you're serving the page from the filesystem, some browsers may give you a little trouble. Safari should work.)

new_data.json含量文件:

[ {"author":"@newAuthor","message":"newMessage","time":"newTime"},
  {"author":"@anotherAuthor","message":"anotherMessage","time":"anotherTime"} 
]

jQuery的:

jQuery:

  // Stores the latest request timestamp
var lastRequestTime = new Date();

  // Make ajax request
$.ajax({
        // URL of data, with the last time
    url: 'new_data.json?time='+lastRequestTime,
    dataType:'json',
    success: function(data) {
             // Update the lastRequestTime
        lastRequestTime = new Date();

            // Get the length of the array returned
        var length = data.length;

            // Walk backward through the array, adding each new item 
            //    to the top of the container
        while(length--) {
                 // Create new .container div
            $('<div/>', {className:'container'})

                 // Append new divs to the $container with proper class and data.
                 // data[length][...] uses the current index stored in the length variable
                .append( $('<div/>', {className:'author', text:data[length]['author']} ) )
                .append( $('<div/>', {className:'message', text:data[length]['message']} ) )
                .append( $('<div/>', {className:'time', text:data[length]['time']} ) )

                 // Prepend $container to the #content div
                .prependTo( '#content' );
        }
    }
});