0

I have a JSON file that looks something like this:

var sourceData = [
{
"id":"c1",
"title":"What color are your eyes?"
}
]

I want to load it via jQuery so I can retrieve the data later:

var myData = $.getScript('data_c1.json', function(data, textStatus){
console.log(data); 
return data
});
console.log(myData)

When I look in the console, 2 things are not what I expect:

  1. the logs hit the console in reverse order
  2. data returns correctly, however myData returns the $.getScript function itself, rather than the data.

For the record, I also tried

$.getJSON("sourceData_c1.json", function(json) {console.log(json);});

and that didn't work for me at all.

I'm stumped. Any help greatly appreciated!

Also, is it valid syntax to place var sourceData = inside the JSON file?

Jasper
  • 75,717
  • 14
  • 151
  • 146
Dan Pouliot
  • 375
  • 2
  • 7
  • 21

1 Answers1

0

If you use $.getJSON() then the output from your file would need to be in JSON format like so (without the variable declaration):

{ "status" : "success",
  "msg"    : "2 items returned.",
  "output" : [
    { "id" : "c1", "title" : "What color are your eyes?" },
    { "id" : "c2", "title" : "What color are your ears?" }
  ]
}

The callback is passed the returned JavaScript file. This is generally not useful as the script will already have run at this point.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page

Source: http://api.jquery.com/jquery.getscript/

Basically when you use $.getScript(), once the callback function has fired that means that the code in the script you've loaded is already in the DOM and can be accessed:

$.getScript('data_c1.json', function(data){
    //since we are in the callback function, the `sourceData` variable should be added to the DOM and accesible
    console.log(sourceData);
});

Note that your script file should have a .js file extension if you are returning JavaScript. If you want to return JSON instead then use $.getJSON() or set the contentType of the AJAX call to json so it will be properly parsed.

Also note that the myData variable was being set to the jqXHR object and not the response of the AJAX call.

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • the JSON output syntax helped me (thank you!), but I still couldn't get it to be available outside of the function, then I found this post which is exactly what I was looking for: http://stackoverflow.com/questions/1739800/variables-set-during-getjson-function-only-accessible-within-function – Dan Pouliot Nov 25 '11 at 22:14