2014-01-22 4 views
0

getJSON() 함수에서 반환 된 값을 변수에 할당하는 문제를 해결하기 위해 노력 중입니다.getJSON()이 완료되었습니다.변수에 할당 된`done()`함수의 반환 값에 접근하는 방법은 무엇입니까?

다음은 타이밍 문제를 해결하지만, done() 함수에서 반환 된 값을 저장하고 변수에 할당하는 또 다른 문제가 발생했습니다.

var fn1 = $.getJSON("/path", function(){ 
}); 

var h = fn1.done(function (results) { 
console.log(results.a_key); // this logs the desired value 
console.log(jQuery.type(results.a_key)); // this logs 'string' 
return results.a_key; 
}); 

alert(h); // alerts [object Object] 

어떻게 변수에 할당 된 done() 함수의 반환 값을 액세스합니까?

이것은 타이밍 문제는 아니며 반환 값에 액세스하는 방법에 관한 것입니다.

위의 방법이 잘못된 경우 누군가가 문제를 해결하고 결과를 함수 외부의 변수에 할당하는 방법을 보여줄 수 있습니까?

+0

당신이 그런 식으로 값을 반환 할 수 없습니다 ...이 처리되기 때문에 비동기 아약스 요청의 결과에 따라 모든 코드는 핸들러 –

+0

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

+0

@ArunPJohny 이전에 물어 보았습니다. 이 질문의 사본으로 여기에 표시된 질문 (http://stackoverflow.com/questions/21238939/how-to-assign-the-return-value-of-a-function-containing-getjson-to-a - 변하기 쉬운), 나는 위가 t를 해결한다 것을 믿는다 그는 타이밍 문제를 가지고 있지만 반환 된 값을 변수에 할당하는 방법을 알지 못합니다. – user1063287

답변

0

솔루션

이있는 솔루션으로 나를 위해 일한 내 대본.대신이 패러다임의

는 :

:

  • function_1 그 결과를 I가 전환 여기 function_2

에서 function_1

  • 사용 a의 비동기
  • a = 결과를 반환
    • a = function_1
    • 사용 b

  • 여기 function_2에서의 function_1 function_1
  • b
  • 을 수행
  • = 결과는 그래서 function_1.done() 기능은 function_2에 대한 용기가되었다.

    예 :

    // here is the function that you are waiting on results from 
    var myGetJsonFunction = $.getJSON("/path", function(){ 
    }); 
    // the following is activated once the above function has run 
    myGetJsonFunction.done(function (results) { 
    var variableFromResults = results.a_key; 
    // use variableFromResults in a function here 
    }); 
    
    // call the 'container' function here 
    $(document).on("click",".form_submit", function (e) { 
    e.preventDefault(); 
    myGetJsonFunction(); 
    }); 
    
  • 0

    donejQuery Deferred object을 반환합니다. 반환 값이 아닙니다. deferred.done()가 지연된 객체를 반환한다

    는 지연된 객체의 다른 방법이 추가되는 .done() 메소드를 포함하여,이 체인 될 수있다.

    (이 그대로 표시되는 값은 "[개체 개체]"입니다 지연된 객체의 [[] ToString].)

    당신이 약속 (또는 다른 비동기 콜백)를 사용하기 시작하면, 당신이 접근 방식을 사용하여을 붙 였지만 괜찮습니다.

    // A done() call always returns the same deferred object (fn1 in this case) 
    // so don't `return` from it. 
    fn1.done(function (results) { 
        console.log(results.a_key); // this logs the desired value 
        console.log(jQuery.type(results.a_key)); // this logs 'string' 
    
        // Do stuff with results here INSIDE the callback 
        // (Could also attach an additional `done` or use `then` as appropriate) 
        alert(results.a_key)  
    }); 
    
    // Code down here is [likely] run before the done callback runs 
    // as the callback is "asynchronous". 
    

    (then 더 복잡한 비동기 실행에 사용이 흐를 때 약속/A 및 jQuery를 이연 객체는 정말 재미가된다.)

    관련 문제