好吧我是jQuery和JSON的新手,但我现在已经这样做了,我从JSON格式的数据库中得到了一些信息,现在我想以一种很好的方式显示结果,但我不知道如何;)< / p>
我想要的是在我的页面上显示5个最新的线程,所以这个脚本会一直尝试加载还是我需要做其他事情?
我希望它显示5个最新的线程,当有一些新线程时我应该向下滑动,底部的6个线程应该消失
这是我的代码
<script type="text/javascript">
$.getJSON('ajax/forumThreads', function(data) {
//$('<p>' + data[0].overskrift + '</p>').appendTo('#updateMe > .overskrift');
$('<div class="overskrift">' + data[0].overskrift + '</div>') {
$(this).hide().appendTo('updateMe').slideDown(1000);
}
//alert(data[0].overskrift);
});
</script>
答案 0 :(得分:0)
服务器端对象的结构是什么? 让我们说你的服务器端对象就是其中之一(c#):
public class ForumThread
{
public string Title { get; set; }
public string Content { get; set; }
public string PostedBy { get; set; }
}
然后你的javascript函数将访问每个属性,如下所示:
<script type="text/javascript">
$.getJSON(
'ajax/forumThreads',
function(data) {
alert(data.Title);
alert(data.Content);
alert(data.PostedBy);
}
});
</script>
如果要返回项目列表,可能有一个容器响应对象,如下所示:
public class ForumThreadList
{
public List<ForumThread> Threads { get; set; }
}
..您将按如下方式访问该列表:
<script type="text/javascript">
$.getJSON(
'ajax/forumThreads',
function(data) {
for (var i = 0; i < data.Threads.length; i++) {
alert(data.Threads[i].Title);
alert(data.Threads[i].Content);
alert(data.Threads[i].PostedBy);
}
}
});
</script>
要添加新项目,您可以尝试以下内容:
假设你的html是:
<body>
<div id="threadContainer">
<!-- javascript will add divs like this:
<div class='threadItem'>Content!</div>
-->
</div>
</body>
您的javascript可能是这样的:
<script type="text/javascript">
$.getJSON(
'ajax/forumThreads',
function(data) {
for (var i = 0; i < data.Threads.length; i++) {
var threadItem = $("<div class='threadItem'>" + data.Threads[i].Title + "</div>");
var existingItemCount = $("#threadContainer > .threadItem").length;
if (existingItemCount >= 5) {
$("#threadContainer > .threadItem:last").remove();
}
if (existingItemCount == 0) {
$("#threadContainer").append(threadItem);
}
else {
threadItem.insertBefore($("#threadContainer > .threadItem:first"));
}
}
}
});
</script>