I have a piece of js code which I would really like to improve but not sure how.
The working version below has a global variable and a separate function declaration which I think could be merged into a anonymous function (Code snipped below: Not working)
Any help or pointers would be appreciated.
Working version:
var Data = {}; // would like to remove the global variable
function callBack() {
$.ajax({
url: "http://host/callBacks/script.js",
//get and execute Script to process json data below
dataType: "script"
});
}
$(document).ready(function() {
$.ajax({
type: "Get",
url: "http://host/data/json/",
success: function(json) {
Data = json; // Would like to just call the callback here
callBack(Data);
},
error: function() {
alert("error");
}
});
});
// Script which gets loaded from callBack
(function(Data) {
var json = $.parseJSON(Data);
$.each(json, function(i, v) {
alert(v);
});
})(Data);
Desired code: Not working
// Error: Length is null or not an object. In jQuery script
var Data = {}; // Ideally would like to remove this from global scope if possible
$(document).ready(function() {
$.ajax({
type: "Get",
url: "http://host//data/json/",
success: function(Data) {
$.ajax({
url: "http://host/callBacks/script.js",
dataType: "script"
});
},
error: function() {
alert("error");
}
});
// Error: Length is null or not an object. In jQuery script
UPDATE: As per adeneo answer:
Still need to the global Data = {}; because the returned immediately executing script takes in as parameter I suppose
var Data = {};
$(document).ready(function() {
function doAjax() {
return $.ajax({
type: "GET",
url: "http://host/data/json/"
});
}
var XHR = doAjax();
XHR.done(function(data) {
Data = data; // <--- If I remove this I get Error:'length' is not or not an object
$.ajax({
url: "http://host/callBacks/script.js",
dataType: "script"
});
}).fail(function() {
alert("error");
});
});
Seems good enough though. Should probably mention that I’am testing this in IE 8. Constraint. Updated tags
1 Answer