Ajax:使用jQuery从JSON添加新的

在页面中,我有这个HTML代码:

 
@Francesc
Hey World!
13/06/2010 11:53 GMT
@SomeOtherUser
Bye World!
13/06/2010 14:53 GMT
@Me
Hey World!
13/06/2010 18:53 GMT

我想问一下,如何从具有更新消息的服务器获取JSON文件并将它们放到顶部,我的意思是在第一个

之上。

另一个问题,在向服务器提交请求时,可以通过GET传递,上次更新的时间? 我该怎么做?
谢谢。

我不知道您的服务器如何提供新数据。

给定一个名为new_data.json的静态文本文件与您的页面位于同一目录中,您可以进行以下ajax请求。

(如果您从文件系统提供页面,某些浏览器可能会给您带来一点麻烦.Safari应该可以工作。)

new_data.json文件的内容:

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

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 $('
', {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( $('
', {className:'author', text:data[length]['author']} ) ) .append( $('
', {className:'message', text:data[length]['message']} ) ) .append( $('
', {className:'time', text:data[length]['time']} ) ) // Prepend $container to the #content div .prependTo( '#content' ); } } });