2012-02-21 3 views
0

jquery ajax를 호출하는 함수에서 값을 반환하는 방법. 나는 다음의 방법에 접근했다. 나는 그것이 정확한지 아닌지를 안다.Jquery ajax 호출 값을 반환하는 방법?

function a(){ 
var a=ajaxFunction(); 
} 

$.ajax({ 
    url: "Handler.ashx", 
    cache: false, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) { 
     _testId = data.Id; 
    } 

return _testId 

}); 

그러나 var a에서 값은 정의되지 않았다. 위 메소드를 사용하여 _testId 값을 반환하지 않습니다. 그것이 틀린 경우 나에게 올바른 접근 방식을 말해주십시오.

답변

1

"Ajax"의 A는 "비동기"를 나타 내기 때문에 콜백 함수를 사용해야합니다.

$.ajax({ 
    'url': 'Handler.ashx', 
    'cache': false, 
    'contentType': 'application/json; charset=utf-8', 
    'dataType': 'json', 
    'success': callback 
); 

function callback(data) { 
    var testID = data.id; 
    console.log(testID); 
} 

당신은뿐만 아니라 그것을 인라인 익명 함수를 사용할 수 있습니다 아약스 결과에 따라

$.ajax({ 
    'url': 'Handler.ashx', 
    'cache': false, 
    'contentType': 'application/json; charset=utf-8', 
    'dataType': 'json', 
    'success': function(data) { 
     var testID = data.id; 
     console.log(testID); 
    } 
); 

모든 코드는 콜백으로 처리해야한다.

0

AJAX 호출이 비동기 적으로 실행되기 때문에 호출이 완료되기 전에 return 문에 도달하므로 반환되는 값은 항상 정의되지 않습니다.

$.ajax({ 
    url: "Handler.ashx", 
    cache: false, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) { 
     _testId = data.Id; 

     // do whatever you need with _testId in here. 
     // You can pass it to another function if you require to modularise your logic, eg. 
     processResult(data) 
    } 
}); 

function processResult(json) { 
    // do stuff with your json here 
} 
0

아마이 작업을 수행 할 것 :

var _testID = false; 

function a(){ 
    ajaxFunction(); 
    if(_testID) 
    { 
     //Do what you need here 
    } 
} 

$.ajax({ 
    url: "Handler.ashx", 
    cache: false, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) { 
     _testId = data.Id; 
    } 
}); 
+1

이 작동하지 않습니다

는 당신은 성공 핸들러 내에서 AJAX 호출의 결과를 처리하는 로직을 변경해야 Matthias와 나는 설명했다. –

관련 문제