在页面中我有以下 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' );
}
}
});
关于jquery - Ajax:使用 jQuery 从 JSON 添加新的 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031957/