2010-01-22 2 views
0

eval 함수를 실행하면 json 응답이 객체로 변환되지 않고 코드가 중단됩니다. prototype.js와 JSON2.js를 사용하여 파싱을 시도했지만 일부는 여기서 잘못 설명하고 있습니까?내 평가가 json 문자열을 객체로 변환하지 않는 이유

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
    <head> 
     <title>Inventory Management</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
     <title>Untitled Document</title> 
     <script src="call.js" type="text/javascript"></script> 
     <script src="prototype.js" type="text/javascript"></script> 
    </head> 
    <body> 
    <div> 
      <p id="resp" >new</p> 
     <script type="text/javascript"> 



    var xhr; 
    var results=getPlants(xhr,results); 
    var plants; 


    function getPlants(xhr,results){ 
     try { 
      xhr=new XMLHttpRequest(); 
      }catch(microsoft){ 
      try{ 
       xhr=new ActiveXObject("Msxml2.XMLHTTP");     
       }catch(othermicrosoft){ 
        try{ 
       xhr = new ActiveXObject("Microsoft.XMLHTTP");    
        }catch(failed){ 
         xhr=false; 
         alert("ajax not supported"); 
        } 
       }    
     } 
     xhr.onreadystatechange= function() { 
     if(xhr.readyState==4 && xhr.status==200) { 
     results = xhr.responseText;      
     }  
} 
    xhr.open("GET","db_interactions.php",true);  
    xhr.send(null); 
    alert("sent"); 
return results; 

} 

plants = eval('('+results+')'); 

document.write(typeof(plants)); 
     </script> 

    </div> 

    </body> 
</html> 

답변

3

비동기 요청을 실행 중입니다. 즉, 데이터가 아직 준비되지 않은 경우에도 함수가 반환됩니다. 하지만 호출은 getPlants이 호출되면 JSON 응답이 준비되었다고 가정합니다. 당신이 기다리지 않아 분명하게 results을 정의하지 않게 만듭니다.

xhr.onreadystatechange 기능 내부

plants = eval('('+results+')'); 
document.write(typeof(plants)); 

는 그것이 작동되도록하거나, 그런데 동기

xhr.open("GET","db_interactions.php",false); 

로 연결을 열려면 넣고, 이 때문에 JSON을 구문 분석 eval를 사용하지 않는 코드가 악의적으로 주입 될 수 있습니다. 대신 JSON 파서를 사용하십시오.

+0

응답이 신뢰할 수있는 출처에서오고, getPlants 정의 외부에서 결과를 인쇄 할 때 적절한 데이터를 반환합니다. 알아 내고자하는 모든 것은 내가 eval 함수를 어떻게 사용하고 있는지 잘못되었습니다. 데이터를 올바르게 역 직렬화시키지 않고 필자가 사용했던 데이터를 직렬화하십시오. –

+1

"신뢰할 수있는"소스가 XSS를 유발하는 다른 곳의 취약점을 가지고 있는지 여부를 알 수 없습니다. 항상 공격면을 최소화하십시오. 게다가 JSON 구문 분석기는'eval'보다 빠를 가능성이 높습니다 (Safari의 eval은 JSON.parse보다 JSON을 구문 분석하는 데 36 % 더 시간이 걸립니다). – kennytm

관련 문제