1

I don't know why I can not read object by using below way

function loadData(){
    $.getJSON('data.json', function(data) {
        $.each(data, function(Index, entry) {
            mem = new user(entry.name, entry.age, entry.location);
            userList.push(mem);
        });
    });
    return false;
}

function fillTable(){
    var html = "";
    console.log(userList);
    console.log(userList[0].name);
    $.each(userList,function(index , user){
       console.log(index);
        html += '<tr>';
        html +=  '<th>'+this.name+'</th>';
        html +=  '<th>'+this.age+'</th>';
        html +=  '<th>'+this.loca+'</th>';
        html += '</tr>'

        console.log(this.name);
    });
    $("#listTable").html(html);
}

the screen shot of above result in console is enter image description here

zwer
  • 24,943
  • 3
  • 48
  • 66
곽성훈
  • 19
  • 1
  • 4

2 Answers2

2

Call fillTable in loadData function, as getJson is async

function loadData(){
            $.getJSON('data.json', function(data) {
                $.each(data, function(Index, entry) {
                    mem = new user(entry.name, entry.age, entry.location);
                    userList.push(mem);
                });
fillTable(); -- call it here
            });

            return false;
        }
Anil
  • 3,722
  • 2
  • 24
  • 49
  • wowowowowowowowowowowwo olololololololololololololololol I solve this problem I don't know why i should code like this and the reason of this but it's working thanks~~~~~~~~~~~~ – 곽성훈 Feb 20 '17 at 06:30
  • To understand async vs sync refer http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean and and please accept as answered. – Anil Feb 20 '17 at 06:40
0
   function loadData(){
        $.getJSON('data.json', function(data) {
            $.each(data, function(Index, entry) {
                mem = new user(entry.name, entry.age, entry.location);
                userList.push(mem);
            });
      fillTable()
        });

        return false;
    }      

   function fillTable(){
        var html = "";
        console.log(userList);
        console.log(userList[0].name);
        var self = this;
        $.each(userList,function(index , user){
           console.log(index);
            html += '<tr>';
            html +=  '<th>'+self.name+'</th>';
            html +=  '<th>'+self.age+'</th>';
            html +=  '<th>'+self.loca+'</th>';
            html += '</tr>'

            console.log(self.name);
        });

}

this will point to inside function, you need to delcare this outside this in outside function.

Try this it may work

Ankit Kumar Gupta
  • 1,256
  • 1
  • 10
  • 23