我找不到完成这个简单 Jquery/Json 任务的方法

I can't find the way to get this simple Jquery/Json task work

我正在努力学习 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>
$(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>');
          }

       });
});

movies 是数组,需要索引器而不是图像或描述。

同样如前所述,循环进入 getjson 内部而不是围绕它

您的代码全都乱七八糟,而且顺序错误。您需要在 获取数据后循环。

$(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. 您想将 for 循环放在 getJSON 成功回调中,因为那是您看电影的时候。
  2. 你每次都覆盖了 $('.row') HTML,所以切换到一个简单的 innerHTML +=,并且还合并了图像和描述的附加。
  3. for 循环中的 i 应该用 var 关键字声明,因为它是 不是全局的。
  4. 最好将生成的 HTML 附加到具有 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>');
           }
       });
   });