2012-03-20 83 views
2

我想要的JSON是在JSON文件,並想在jQuery的模板來訪問我該怎麼辦,你的幫助,理解訪問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文件現在我想訪問該名稱只提交如何從json文件訪問名稱字段

$(document).ready(function(){ 

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

});

要訪問的字段,但錯誤顯示爲數據[0] undifined

回答

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"); 

}); 
+0

感謝很多的答案,它奇妙的作品很好 – 2012-03-20 06:48:51

+0

感謝您的幫助...它運作良好 – 2012-03-20 06:51:19

+0

我想從json文件中訪問名稱字段...你能幫我嗎 – 2012-03-20 07:03:01