通过别名获取Javascript字符串变量的值

时间:2014-12-10 04:41:48

标签: javascript json global-variables eval alias

我编写了一个Javascript函数,可以在任何浏览器中从服务器或本地文件中检索JSON数据。此代码从以下任一位置摘要JSON数据:(a)XMLHttpRequest响应,或(b)导入的脚本变量。

对于后一种情况,此代码需要变量'JSONdata'。它不是将其内联在两个(或更多)位置,而是初始化为全局常量JSCRIPTVAR。这是为了易读性和维护 - 如果数据文件使用不同的值,则更改。你会看到代码使用eval函数来提取(指向我们的)JSON数据 - 有点太接近实际数据了。我的问题是,如何在不使用(可怕的)eval函数的情况下通过别名JSCRIPTVAR读取原始变量'JSONdata'的值?

我已尝试过此处所述的闭包和其他方法(Reference a Javascript variable by a text alias),但无法获取JSON数据,只能获取变量名称或“未定义”。

var JSCRIPTVAR = "JSONdata";        // any variable name less than 10 characters or less
function digestJSON(response, JSONobjName) {
    if (typeof response == 'string') 
        JSONstring = response;
    else if (typeof JScriptVar !== 'undefined' && typeof JSCRIPTVAR.valueOf() !== 'undefined')  
        JSONstring = eval(JSCRIPTVAR.substring(0, 10));     // ensure that we don't take in any malicious code
    try {
        // this method assigns the JSON data to a global object using JSONobjName, so can support multiple JSON objects
        window[JSONobjName] = JSON.parse(JSONstring);       // Parse JSON string into object - IE 8+ supports JSON.parse()
        console.log("Successfully digested JSON. Data is now available via DOM methods.");
    } catch (e) {
        alert("Error parsing the '" + JSONobjName + "' file'. Check that the file is properly formatted.");
        console.error("JSON parsing error: ", e + ", type: " + this.type);
    }
}

在使用匿名回调的3个函数中调用函数digestJSON:loadViaXHR2,loadViaXHR1和loadViaJScript。后者是通过Javascript文件导入JSON数据的那个(参见下面的示例)。调用时,'callback'参数将设置为'digestJSON'。

function loadViaJScript(urlSpec, JSONobjName, callback, isAsync) {
    console.log("Attempting to read JSON data using Javascript methods.");
    var script = document.createElement('script');
    var parent = document.getElementsByTagName('head').item(0) || document.documentElement;
    script.type = "text/javascript";
    script.onerror = function(e) {
        alert("Error loading the '" + JSONobjName + "' file: '" + urlSpec + "'. Check that the file exists.");
        console.error("Error loading via Javascript: ", e + ", type: " + this.type);
    }
    script.src = urlSpec;
    parent.appendChild(script);
    script.onload = function() { 
        callback(null, JSONobjName); 
    };
}

示例数据(简单示例): var JSONdata ='{“blue”:“is ok”,“red”:“is my fave color”}';

2 个答案:

答案 0 :(得分:3)

也许这个事实会对你有所帮助:全局范围内的任何变量都可以作为window的属性进行访问。所以,如果你有

var something=1;
var VARNAME="something";

以下是等效的:

console.log(something);//1
console.log(eval(VARNAME));//1
console.log(window[VARNAME]);//1
console.log(window.something);//1

以下是一些例子:

<script>
var something=1;
var SCRIPTVAR="something";

console.log(eval(SCRIPTVAR));//1
console.log(something);//1
console.log(window[SCRIPTVAR]);//1
console.log(window.something);//1

eval(SCRIPTVAR+"++");

console.log(eval(SCRIPTVAR));//2
console.log(something);//2
console.log(window[SCRIPTVAR]);//2
console.log(window.something);//2

window[SCRIPTVAR]++;

console.log(eval(SCRIPTVAR));//3
console.log(something);//3
console.log(window[SCRIPTVAR]);//3
console.log(window.something);//3


window.something++;

console.log(eval(SCRIPTVAR));//4
console.log(something);//4
console.log(window[SCRIPTVAR]);//4
console.log(window.something);//4
</script>

答案 1 :(得分:0)

digestJSON的最终代码,由chiliNUT修复(初始化&#39; JSONdata&#39;然后通过Window对象访问我们的全局别名):

var JSONdata = "";                // initialise before loading
var JSCRIPTVAR = "JSONdata";      // set global constant for referencing
function digestJSON(response, JSONobjName) {
    console.log("Attempting to digest JSON data using JSON parsing methods.");
    var JSONstring = "";
    if (typeof response == 'string') 
        JSONstring = response;
    else if (JSCRIPTVAR && typeof window[JSCRIPTVAR] == 'string' && window[JSCRIPTVAR].length > 0) 
        JSONstring = window[JSCRIPTVAR];
    try {
        // this method assigns the JSON data to a global object using JSONobjName, so can support multiple JSON objects
        window[JSONobjName] = JSON.parse(JSONstring);       // Parse JSON string into object - IE 8+ supports JSON.parse()
        console.log("Successfully digested JSON. Data is now available via DOM methods.");
    } catch (e) {
        alert("Error parsing the '" + JSONobjName + "' file'. Check that the file is properly formatted.");
        console.error("JSON parsing error: ", e + ", type: " + this.type);
    }
}

Hooray,不再需要eval功能!感谢所有发表评论的人。