I've been struggling with getting the data out of an AJAX call using jQuery. I'm using RequireJS so my JavaScript can be more maintainable/modular. I've only been using RequireJS for a few days, so I may or may not be doing this right. Just looking for a way to keep my JS modular and clean.
Here is what I have so far. I know for a fact that it's getting the correct data because if I console.log(data[Math.floor(Math.random()*data.length)])
, the data is there. The JSON file is long so I won't show you that, just take my word for it — it works.
var maze;
define(["jquery"], function($){
$.ajax("js/mazes.json", {
dataType: "json",
type: "get",
success: function(data){
var maze = data[Math.floor(Math.random()*data.length)];
}
});
return {
randomMaze: maze
};
});
I also tried this (declaring maze
within anonymous function)
define(["jquery"], function($){
var maze;
$.ajax("js/mazes.json", {
dataType: "json",
type: "get",
success: function(data){
var maze = data[Math.floor(Math.random()*data.length)];
}
});
return {
randomMaze: maze
};
});
I don't know what I'm doing wrong. Just trying to return data[Math.floor(Math.random()*data.length)]