2009-08-14 4 views
0

jquery를 통해 웹 서비스에 대한 ajax 호출을 수행하는 매우 간단한 javascript 클래스가 있습니다. 데이터를 성공적으로 반환하지만 데이터를 설정 한 변수를 통해 검색 할 수 없습니다. 나는 모든 아약스 이벤트에 대한 이벤트 핸들러를 설정했기 때문에 비동기식 아약스 호출의 문제라고 생각하지 않지만 일부는 발생시키지 않습니다. 나는 무엇이 잘못되었는지 전혀 모른다.jQuery Ajax와 관련된 문제 타이밍

자바 스크립트 : 여기에 전체 코드는

function testClass(){ 
    this.returnData = ""; 
    this.FireAjax = function(){ 
     $.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?", 
      function(data){ 
       this.returnData = data.d; 
       alert(data.d); 
      } 
     ); 
    } 

} 

HTML 페이지 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script type="text/javascript" src="http://localhost/mywebapp/js/jquery-1.3.2.min.js"></script> 
<script type="text/javascript" src="testClass.js"></script> 

<script type="text/javascript"> 
    $(document).ready(function(){ 

     var obj = new testClass(); 

     $("#debug").ajaxError(function(event, request, settings){ 
      $(this).append("<b>Ajax Error!</b><br />"); //this does not fire 
     }); 

     $("#debug").ajaxSend(function(evt, request, settings){ 
      $(this).append("<b>Ajax Send!</b><br />"); //this does not fire!? 
     }); 

     $("#debug").ajaxStop(function(){ 
      $(this).append("<b>Ajax Stopped</b><br />"); //this fires 
     }); 

     $("#debug").ajaxComplete(function(event,request, settings){ 
      $(this).append("<b>Ajax Completed!</b><br />"); //this fires 
      $(this).append("<h2>" + obj.returnData + "</h2>"); //this returns an empty string!!!!!! 
     }); 

     $("#debug").ajaxSuccess(function(evt, request, settings){ 
      $(this).append("<b>Ajax Successful!</b><br />"); //this fires 
     }); 

     $("#debug").ajaxStart(function(){ 
      $(this).append("<b>Ajax Started!</b><br />"); //this fires 
     }); 

     obj.FireAjax(); 
    }); 
</script> 
</head> 

<body> 
<div id="debug"> 

</div> 
</body> 
</html> 

추가 정보 : 내 HTML 페이지에서 complete 이벤트를 제거하고에 전화를 걸 경우 obj.returnData 내 중지 이벤트 (아마 내 HTML 완료 이벤트 내 testClass 전체 기능을 덮어 쓴다고 생각), 나는 같은 결과를 얻을.

+0

"이"testClass.js에서 익명 함수에 무엇을 가리키는가? –

+0

"this"는 객체의 인스턴스를 참조해야합니다 ... 그렇지 않다고 생각합니까? –

+0

ajaxSend가 발사하지 않는 이유는 알 수 없습니다. –

답변

1

귀하의 문제는 여기에 있습니다 :

this.returnData = data.d; 

this 익명 함수는 jQuery를 옵션 객체가 아닌 개체의 인스턴스를 참조 내부.

이 시도 :

function testClass(){ 
    this.returnData = ""; 
    var that = this; 
    this.FireAjax = function(){ 
     $.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?", 
       function(data){ 
         that.returnData = data.d; 
         alert(data.d); 
       } 
     );  
    } 

} 
+0

그게 다야! 정말 고마워. 왜 ajaxSend 이벤트가 (호기심에서) 발사되지 않는지 아시겠습니까? –