2012-11-18 5 views
0

저는 막혔습니다. 필을 호출하고 JSON.parse로 결과를 반환하는 두 가지 함수가 있습니다. 하지만 내가 console.log 결과가 "정의되지"얻을. XHR 요청이 완벽하게 정상적으로 출력을 보여줍니다 받고 크롬 메신저에 따르면XHR 요청이 정의되지 않았습니다.

result = call_data('./chk_login.php',0); 
console.log(result); 

:

function caller(url,cfunc){ 
     if (window.XMLHttpRequest) 
      {// code for IE7+, Firefox, Chrome, Opera, Safari 
       xmlhttp=new XMLHttpRequest(); 
      } 
     else 
      {// code for IE6, IE5 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
       xmlhttp.onreadystatechange=cfunc; 
       xmlhttp.open("GET",url,true); 
       xmlhttp.send(); 
} 
function call_data(url,data){ 
    caller(url,function(){ 
     if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
      return(JSON.parse (xmlhttp.responseText)); 
     } 
    });           
} 

통화가 여기에 있습니다 :

내 요청을 처리하는 기능입니다. 하지만 console.log는 정의되지 않은 것을 보여줍니다 ... 그래서 이것은 내 PHP 스크립트입니다.

<? 
    $var = 1; 
    echo json_encode($var); 
    exit; 
?> 

무엇이 문제의 원인 일 수 있습니까 ???

희망을 도울 수 있습니다. 감사합니다.

+0

JQuery와 같은 Javascriot 프레임 워크를 사용하지 않는 이유는 무엇입니까? – Tchoupi

+2

jQuery 나 그 프레임 워크를 사용하고 싶지 않기 때문에? – Sir

+0

'call_data'는 아무 것도 반환하지 않습니다 ... – Musa

답변

1

이것은 비동기식이므로 (AJAX의 A가 의미하는 바에 따르면) 간단히 return 값을 가져올 수없고 마술처럼 돌아올 수는 없습니다. 대신, 콜백 내에서 데이터를 조작하십시오 (이미 80 % 정도).

function call_data(url,data){ 
    caller(url,function(){ 
     if (xmlhttp.readyState==4 && xmlhttp.status==200){ 
      console.log(JSON.parse (xmlhttp.responseText)); 
      ajaxResult = JSON.parse (xmlhttp.responseText); 
     } 
    }); 
} 

var ajaxResult; 
관련 문제