【发布时间】:2016-11-11 09:35:16
【问题描述】:
所以我有这段代码,但我没有让它工作,我在一个基于 jquery 的博客上工作,其中包含 JSON 加载的对象,但我碰壁了。我需要将对象属性放入我体内的 div 元素中以制作博客文章。我应该能够在 JSON 文件中放一个新帖子,它应该出现在正文中。我不知道该怎么做,到目前为止我的代码看起来像这样:
$( document ).ready(function() {
$.ajax({
dataType: "json",
url: "posts.json",
}).done(function(resp){
for(var p in resp){
if(resp.hasOwnProperty(p)) continue;
var title = resp[p].title;
var content = resp[p].content;
var author = resp[p].author;
var date = resp[p].date;
var image = resp[p].image;
}
});
});
和 JSON 文件:
{
"post1" : {
"title": "My day",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "robert",
"image" : "../blogg/img.jpg"
},
"post2" : {
"title": "This right here",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "robert",
"image" : "../blogg/img.jpg"
},
"post4" : {
"title": "Min vackra",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "klara",
"image" : "../blogg/img.jpg"
}
}
首先我创建的变量是未定义的,为什么?
如何使变量包含不同的帖子?
对不起,我编程很烂……
【问题讨论】:
-
您需要更改条件
if(resp.hasOwnProperty(p) == false) -
为什么会有不同?那应该是 === 吗?
-
如何在 html 中呈现数据?