我有一段 js 代码,我真的很想改进,但不知道如何改进。下面的工作版本有一个全局变量和一个单独的函数声明,我认为可以合并到一个匿名函数中(代码如下:不工作)
任何帮助或指示将不胜感激。
工作版本:
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);
所需代码:不工作
// 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
更新:根据 adeneo 的回答:仍然需要全局 Data = {}; 因为返回的立即执行脚本作为参数我想
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");
});
});
不过似乎还不错。可能应该提到我正在 IE 8 中对此进行测试。约束。更新的标签