2012-12-12 2 views
5

고정! 감사! 아래의 "수정 된 코드"를 참조하십시오.jQuery 반환 값 undefined

목표는 대화 상자에서 데이터를 다시 얻는 것입니다. 많은 기사를 보았지만 그 중 어떤 것도 작동하지 못하기 때문에 웹 서비스를 사용하여 대화 상자와 기본 페이지간에 데이터를주고 받기로 결정했습니다.

웹 서비스에서 되돌아 오는 값을 읽는 코드를 제외한 모든 코드가 제자리에 있습니다. 디버거에서 데이터가 다시 전달되는 것을 볼 수 있지만 호출자에게 반환하면 반환 된 데이터는 정의되지 않습니다.

jQuery 함수 getLocal은 AJAX를 호출하고 좋은 데이터를 다시 가져 오지만,이를 호출하는 함수 (verbListShow)로 돌아 오면 반환 값은 "정의되지 않음"입니다.

이것은 주로 jQuery로 작성된 ASP.NET 페이지에서 발생하며 jQuery 대화 상자를 엽니 다.

function getLocal(name) { 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      var rtn = data.d; 
      return rtn; 
     } 
    }); 
} 

위의 코드는 작동하지만, 호출하면 rtn은 정의되지 않습니다.

function verbListShow(dutyNumber) { 

    $('#dlgDutyList').dialog({ 
     modal: true, 
     show: "slide", 
     width: 250, 
     height: 250, 
     open: function (event, ui) { 
      setLocal("DUTYNUMBER", dutyNumber); 
     }, 
     buttons: { 
      "Select": function() { 
       var id = getLocal("VERBID"); // <*** Returns undefined 
       var verb = getLocal("VERB"); // <*** Returns undefined 
       $.ajax({ 
        type: "POST", 
        async: false, 
        url: "WebServices/FLSAService.asmx/SetDuty", 
        dataType: 'json', 
        contentType: 'application/json; charset=utf-8', 
        data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: verb }), 
        success: function (data) { 
         data = $.parseJSON(data.d); 
         if (data.ErrorFound) { 
          showMessage(data.ErrorMessage, 2, true); 
         } 
         else { 
          log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')'); 
         } 
        }, 
        error: function (XMLHttpRequest, textStatus, errorThrown) { 
         alert("updateDuty: " 
          + XMLHttpRequest.responseText); 
        } 
       }); 

       $(this).dialog("close"); 
      }, 
      Cancel: function() { 
       $(this).dialog("close"); 
      } 
     } 

    }); 
    $('#dlgDutyList').dialog('open'); 

FIXED CODE :

function getLocal(name) { 
var rtn = ""; 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      rtn = data.d; 
     } 
    }); 
return rtn; 
} 
+0

이름을 게시 할 때 웹 서비스는 무엇을 반환합니까? 그것에 필드가 있습니까? 일부 샘플 데이터를 보여줍니다. –

+0

'return rtn;'아약스 성공 콜백에서 리턴 할 수 없습니다. getLocal 함수를 사용하지 않거나 jqXHR 객체를 반환하는 것이 좋습니다. –

답변

6

그것은 기적 그것을 사용하는 AJAX의 목적을 패배 (AJAX 비동기 자바 스크립트와 XML의 약자) 여기에 발신자입니다.

이제하지 return a를 성공 방식과 가치,하지만 당신은 다음 변수에 저장 할 수는

function getLocal(name) { 
    var returnValue; 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      returnValue = data.d; 
     } 
    }); 
    return returnValue; 
} 

그러나이 적절한 방법은 deferred object

을 사용하는 것입니다 것을 반환 할 수 있습니다
function getLocal(name, resultset) { 
    return $.ajax({ 
     type: "POST", 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      resultset[name] = data.d; 
     } 
    }); 
} 

0 전화
3

모든 것은 $ .ajax 함수가 비동기 동작 때문에 어떤 값도 반환하지 않기 때문에 제 조언은 "콜백"이라는 getLocal 메서드의 두 번째 매개 변수를 만드는 것입니다.

적절한 방법과 같이 그것을 할 수 있습니다 :

function getLocal(name, callback) { 
    $.ajax({ 
     type: "POST", 
     async: false, 
     url: "WebServices/FLSAService.asmx/GetLocalVariable", 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ name: name }), 
     success: function (data) { 
      var rtn = data.d; 
      callback(rtn); 
     } 
    }); 
} 

그런 다음 주 코드가 (비동기 코드)처럼 보이고 있습니다

//some code here 
buttons: { 
      "Select": function() { 
       getLocal("VERBID", function(id) { 
        getLocal("VERB", function(verb) { 
         $.ajax({ 
          type: "POST", 
          async: false, 
          url: "WebServices/FLSAService.asmx/SetDuty", 
          dataType: 'json', 
         //some code here 
        }); 
       }); 
//some code here 

두를 만들기 위해,이 코드를 개선하기 위해 한 번에 비동기 호출을 사용하면 jQuery Deferred 객체를 사용할 수 있으며 모든 Ajax 호출이 적절한 응답을 얻은 직후에 .resolve(data)을 실행합니다.

+0

응답자 모두에게 감사드립니다. 당신의 도움으로 코드가 빨리 작동합니다. –