1

I have json file

{
 "arr": [
  {
    "text1": "first",
    "text2": "second",
  },
  {
    "text11": "first",
    "text22": "second",
  }
 ]
}

and I want get this object.

$.ajax({
    url: '../test.json',
    dataType: 'json',
    type: 'get',
    cache: 'false',
    success: function(data) {
        console.log(data.arr);
    }
});

and this are working. But if I want assign a value to a variable, it doesn't work.

    success: function(data) {
        var arrTest = data.arr;
    }

    console.log(arrTest);

return arrTest is not defined

  • 2
    because you are accessing attTest outsite of success function – Adam Wolski Feb 24 '17 at 22:12
  • Your json is not valid. Remove comma after "Second", – smoore4 Feb 24 '17 at 22:32
  • The problem is twofold: 1. `arrTest` is local to the function it's declared in and will be deleted when the function has completed. You read this variable outside that function, therefore it's undefined. 2. Even if you would declare it globally, `console.log()` accesses it before the **async** call has initialized `data`. – iloo Feb 24 '17 at 22:44

0 Answers0