gpt4 book ai didi

javascript - 改进js代码去掉全局变量和函数

转载 作者:行者123 更新时间:2023-11-30 13:15:54 25 4
gpt4 key购买 nike

我有一段 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 的回答:还是需要global 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 中对此进行测试。约束。更新标签

最佳答案

$(function() {
function doAjax() { //put inside function
return $.ajax({ //return deffered object
type: "GET",
url: "/data/json/" //X domain not supported
});
}

var XHR = doAjax(); //do ajax call
XHR.done(function(data) { // use deffered object
var json = $.parseJSON(data); //why would you need to get an external script just to parse some JSON?
$.each(json, function(i, v) {
alert(v);
});
}).fail(function() {
alert("error");
});
});

关于javascript - 改进js代码去掉全局变量和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12032453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com