我正在努力学习json的基础知识。我想使用jquery。我写了一个简单的json文件,如下所示;我想把它叫做html页面。你能告诉我我的代码有什么问题吗? 提前谢谢。
json文件
{"movies" : [
{"image":"hfgh5.jpg",
"description":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency."},
{"image":"fdg.jpg",
"description":"The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son."},
{"image":"36frg.jpg",
"description":"The lives of two mob hit men, a boxer, a gangster's wife, and a pair of diner bandits intertwine in four tales of violence and redemption."}
]
}
JavaScript的:
$(document).ready(function () {
for (i = 0; i < movies.length; i++) {
$.getJSON('film.json', function () {
$('.row').html('<img src="' + movies.image[i] + '">');
$('.row').html('<p>' + movies.description[i] + '</p>');
});
}
});
HTML:
<body>
<div class="container">
<div class="row"></div>
</div>
</body>
答案 0 :(得分:0)
您的代码混乱并且顺序错误。 获取数据后,您需要遍历数据。
$(document).ready(function(){
// Your callback needs a variable to store the data in
$.getJSON('film.json', function(data){
// data is your entire object, data.movies is an array
for (var i = 0; i < data.movies.length; i++) {
// .html() will *replace* the HTML, you want to .append()
$('.row').append('<img src="' + data.movies[i].image + '">');
$('.row').append('<p>' + datamovies[i].description + '</p>');
}
});
});
答案 1 :(得分:0)
只是一些问题,但除此之外还有一个良好的开端。
getJSON
成功回调中,这就是你有电影的时候。 innerHTML +=
,并整合了图像和说明的附加内容。 i
应该使用var
关键字声明
不是全球性的。id
的元素也是一件好事,因为可能会有多个$('.row')
<强> HTML 强>
<body>
<div class="container">
<div class="row" id="movies_row"></div>
</div>
</body>
<强> jquery的:强>
$(function() {
$.getJSON('film.json', function(data) {
var movies = data.movies;
for (var i = 0, j = movies.length; i < j; i++) {
var movie = movies[i];
$('#movies_row')[0].innerHTML += '<img src="'+movie.image+'"><p>'+movie.description+'</p>');
}
});
});
答案 2 :(得分:-1)
$(document).ready(function () {
$.getJSON('film.json', function () {
for (i = 0; i < movies.length; i++) {
$('.row').html('<img src="' + **movies[i].image** + '">');
$('.row').html('<p>' + **movies[i].description** + '</p>');
}
});
});
电影是数组,需要索引器而不是图像和描述。
同样如前所述,循环进入了getjson而不是它周围