Ajax:使用jQuery从JSON添加新内容
发布时间:2020-12-16 02:56:53 所属栏目:百科 来源:网络整理
导读:在页面中,我有这个 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
在页面中,我有这个
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应该可以工作.) 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 $('<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' ); } } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |