2014-12-10 2 views
1

모든 브라우저에서 서버 또는 로컬 파일에서 JSON 데이터를 검색하는 Javascript 함수를 작성했습니다. 이 코드는 JSON 데이터를 (a) XMLHttpRequest 응답 또는 (b) 가져온 스크립트 변수 중 하나에서 다이제스트합니다.별칭을 통해 Javascript 문자열 변수 값 가져 오기

후자의 경우이 코드는 변수 'JSONdata'를 필요로합니다. 두 개 이상의 장소에 인라인하지 않고 전역 상수 JSCRIPTVAR로 초기화됩니다. 데이터 파일이 다른 값을 사용하면 변경하기 쉽도록 읽기 쉽고 유지 관리됩니다. 코드에서 eval 함수를 사용하여 JSON 데이터 (JSON 데이터에 대한 포인터)를 추출하는 것을 볼 수 있습니다. 실제로는 편안함을 위해 실제 데이터에 너무 가깝습니다. 내 질문은, 어떻게 (기본 변수) 'JSONdata'별칭 JSCRIPTVAR를 통해 (무시 무시한) 평가 기능을 사용하지 않고 원시 변수의 가치를 읽습니까?

여기에 설명 된 클로저 및 다른 방법을 시도했지만 (Reference a Javascript variable by a text alias) JSON 데이터를 가져올 수 없으며 변수 이름 또는 '정의되지 않음'만 가져올 수 있습니다. loadViaXHR2, loadViaXHR1 및 loadViaJScript :

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); 
    } 
} 

함수 digestJSON 익명 콜백을 사용 3 개 기능에 호출된다. 후자는 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 = '{ "블루", "빨간색" "괜찮습니다": "내 페이브 색"}';

+0

아마도'digestJSON()'을 호출하는 코드를 보는데 도움이 될 것입니다. –

+0

Thanks @GarciaHurtado. 나는 제출을 기뻐했다. 정말 간단한 질문입니다. 모든 JSON 항목이 아무나 벗어나지 않기를 바랍니다. – wmclaxton

+0

'JSONobjName'과 같은 전략을 사용하지 않는 이유는 무엇입니까? – Bergi

답변

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 

은 몇 가지 예입니다 : digestJSON에 대한

<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> 
+0

당신 말이 맞아요. 이 스텁이 작동하고 창 개체를 참조하는 마지막 줄이 함수 내부에있을 수 있습니다. var something = 1; var SCRIPTVAR = "무언가"; 경고 ("뭔가를 얻었습니다 :"+ 창 [SCRIPTVAR]); // returns 1 그러나 JSON 데이터를 비동기 적으로 할당했기 때문에 여전히 JSCRIPTVAR에서 작동하지 않습니다. – wmclaxton

+1

chiliNUT, 나는 당신에게 upvote하지만 나는 평판 포인트가 없습니다. 누군가가 "eval이이 상황에서 합법적이라고"말하지 않는 한 당신에게 답을 줄 수 있습니다. – wmclaxton

+0

비동기는 콜백 함수에서 처리해야합니다. 그 이상 ... 비동기 액세스의 문제는 가변 변수 이름의 문제와는 다른 것입니다. 따라서 문제를 보여주고 작은 질문을 한 후 새로운 질문을하십시오. – chiliNUT

0

마지막 코드, chiliNUT에 의해 수정과 (초기화 'JSONdata'를 선택하고 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); 
    } 
} 

만세, 더 이상 평가 기능이 필요하지 않습니다! 의견을 올린 모든 분들께 감사드립니다.

관련 문제