2013-04-02 3 views
0

에 난 내 콘솔 (firbug) 내가 얻을에 자바 스크립트 함수기능 내용의 실행 순서

function myfunction() { 

    var url = location.href; 
    var ajaxRespose; 

     $.ajax({ 
      type:"GET", 
      url: url, 
      cache:false, 
      dataType: "text", 
      success: function(response) { 
       var data = $.parseJSON(response); 
       ajaxRespose = data; 
       console.debug("ajaxRespose ==>:"+ajaxRespose); 
      } 
     }); 
     console.debug("first ajaxRespose: " +ajaxRespose); 
    } 
    return false; 
} 

가 없습니다 : 아약스 호출 후 실행 이유

first ajaxRespose: undefined 

ajaxRespose ==>:[object Object] 

내 질문은의 " 첫 번째 "console.debug. 추신 : 나는 기능을 단순화했습니다. (기능은 정상적으로 작동하지만 문제는 순서대로 실행됩니다.)

+0

'dataType : "text"를 바꿉니다. , with'data type : "json", ' –

+2

이것은 비동기 요청이 작동하는 방식으로, 첫 번째 디버그는 ajax 요청이 완료되기 전에 실행됩니다. – David

+0

가능한 [AJAX 호출에서 응답을 반환하는 방법?] (http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –

답변

1

때문에, 이벤트의 순서는 다음과 같이 일 :. "병렬"아약스 Asynchronus입니다 beacuse이다

$.ajax(...); // executes AJAX request 
console.debug("first ajaxResponse:" + ajaxRespose); // undefined 

/* some time later, we receive AJAX response */ 

// it executes the success function from the original AJAX request 
console.debug("ajaxRespose ==>:"+ajaxRespose); // [object Object] 
+0

감사합니다, 내가 추가 "비동기 : 거짓"와 같은 지금은 무엇입니까 출력 : ajaxRespose ==> [개체 개체] 첫 ajaxRespose : [개체 개체] – Shahzeb

+0

헤이 온몸은 (위 또는 아래로 투표와 좋은 후원자하시기 바랍니다) (좋은 또는 나쁜) 답변이나 의견. – ncm

1

AJAX는 비동기식입니다 (따라서 이름). "첫 번째 ajaxRespose"를 기록하는 콘솔 로그는 AJAX 요청이 완료되기 전에 실행되기 때문에 정의되지 않은 것입니다. 그러면 AJAX 요청이 완료되고 응답을 받게됩니다. $.ajax()비동기입니다

1

.... 작품이 발생 .. 그래서 때 Ajax 호출이 실행되고, 다른 코드가 병렬로 실행됩니다. Ajax 호출이 완료되면 ajax.callback 함수가 호출되어 ajaxRespose가 실행될 때 Ajax.callback 함수의 콜백 함수 내에 정의하는 것이 유일한 방법입니다.