在页面中,我有这个
HTML代码:
<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文件并将它们放到顶部,我的意思是在第一个< div class =“container”>之上.
另一个问题,在向服务器提交请求时,可以通过GET传递,上次更新的时间?我该怎么做?
谢谢.
解决方法
我不知道您的服务器如何提供新数据.
给定一个名为new_data.json的静态文本文件与您的页面在同一目录中,您可以进行以下ajax请求.
(如果您从文件系统提供页面,某些浏览器可能会给您带来一些麻烦.Safari应该可以工作.)
[ {"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 $('<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' ); } } });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。