在jquery模板中访问json文件

时间:2012-03-20 06:32:30

标签: json jquery

我希望json在json文件中并想要在jquery模板中访问我该怎么做才能得到你的帮助

var movies = [
  { Name: "The Red Violin", ReleaseYear: "1998" },
  { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
  { Name: "The Inheritance", ReleaseYear: "1976" }
  ];

var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

/* Compile the markup as a named template */
$.template( "movieTemplate", markup );

/* Render the template with the movies data and insert
   the rendered HTML under the "movieList" element */
$.tmpl( "movieTemplate", movies )
  .appendTo( "#movieList" );

现在我正在尝试访问名称,但我只能从json文件中访问名称字段

$(document).ready(function(){

        $.getJSON('dat.js', function(data) {
             $( "#movieTemplate" ).tmpl( data[i].name).appendTo( "#movieList" );
            });

});

想要访问该字段,但显示为数据[0]的错误是未定义的

1 个答案:

答案 0 :(得分:2)

使用jQuery.getJSON()加载json文件内容:

var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

/* Compile the markup as a named template */
$.template( "movieTemplate", markup );

$.getJSON('movies.json', function(data) {

  // 'data' is the json loaded and parsed from the file
  $.tmpl( "movieTemplate", data )
     .appendTo( "#movieList" );

});