在页面中,我有这个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>
Run Code Online (Sandbox Code Playgroud)
我想问一下,如何从具有更新消息的服务器获取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"}
]
Run Code Online (Sandbox Code Playgroud)
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' );
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4884 次 |
| 最近记录: |