Dan
Dan

Reputation: 1295

getJSON help jQuery

so i know this bit of code works

$.getJSON('data/book.json', function(jd) {

         $('#stage').html('<p> id: ' + jd.data.productTypeList[0].id + '</p>');
         $('#stage').append('<p>name : ' + jd.data.productTypeList[0].name+ '</p>');
         $('#stage').append('<p> longName: ' + jd.data.productTypeList[0].longName+ '</p>');

});

the problem is i am trying to update it to here and getting an error

var jqxhr = $.getJSON("data/book.json")
          .success(function(data, status, xhr) { 
            $.each(data, function(i,item){
              //create book for each item and then insert into the collection
              tmpItem=new Book({id:item.data.productTypeList[0].id,category:item.data.productTypeList[0].name,name:item.data.productTypeList[0].longName});
              self.add(tmpItem);
            });
            //dispatch customized event
            self.trigger("fetchCompleted:Books");
          })
          .error(function() { alert("error"); })
          .complete(function() {
                console.log("fetch complete + " + this);
          });
      }

but i cant get this to work and keep getting an error of item.data is undefined.

once i have sorted that i plan on changing the 0 to i an so that it will pick up all the results in the array

thanks

Upvotes: 0

Views: 104

Answers (3)

Riplexus
Riplexus

Reputation: 340

Try this:

if (!('productTypeList' in data)) {
    //catch illegal response 
}
$.each(data.productTypeList, function(i,item){
    //create book for each item and then insert into the collection
    tmpItem=new Book({id:item[i].id,category:item[i].name,name:item[i].longName});
    self.add(tmpItem);
});

Upvotes: 0

cjc343
cjc343

Reputation: 3765

Set a breakpoint on the line containing item.data in your favorite browser console.

While there, look at the data, i, and item variables and make sure they contain what you expect.

It should be quite easy to determine what's wrong and fix it at that point.

Upvotes: 0

MarcoK
MarcoK

Reputation: 6110

Your $.each is wrong.

  1. You each over the data, not the items in the data.
  2. You ask the "item" again inside the each, which isn't available.

Try this:

$.each(data.productTypeList, function(i, productType){
    // Use "productType" here, example:
    // new Book( { id: productType.id } )
}

Upvotes: 2

Related Questions