Arnab Shaw
Arnab Shaw

Reputation: 539

accessing the json file in jquery template

I want the json to be in the json file and want to access in the jquery template how can i do that your help be appreciated

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

now i am trying to access the name filed only how can i access the name field from json file

$(document).ready(function(){

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

});

want to access the field but error showing as data[0] is undifined

Upvotes: 2

Views: 242

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

Use jQuery.getJSON() to load the json file content:

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

});

Upvotes: 2

Related Questions