2017-01-28 2 views
0

다음은 webapi 메서드를 호출하는 Jquery의 코드 조각입니다. GetAllEmployees() 메서드를 호출하면 undefined이라는 데이터가 반환되고 메서드는 Success이 호출됩니다. 왜 그런가? 난 내가 함수를 호출하면 결과를 원하는jquery 실패한 webapi 호출

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>GetAllCust</title> 
    @*<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>*@ 

    <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
    <script type="text/javascript"> 
     function GetAllEmployees() 
     { 
      var Result; 
      // debugger; 
      jQuery.support.cors = true; 
      $.ajax({ 
       url: 'http://localhost:61883/APIService/api/Employee/GetAllEmployees',// service call 
       type: 'GET', 
       dataType: 'json', 
       success: function (data) 
       { 

        Result = data;// Not returning the data 
        $.each(data, function (index, employee) 
        { 
         console.log(employee.EmpName); 
         alert(employee.EmpName); 
        }); 
       }, 
       error: function (x, y, z) { 
        alert(x + '\n' + y + '\n' + z); 
       } 
      }); 
      return Result;//Not sending the result 
     } 
     // Calling the method here 
     $(document).ready(function() 
     { 
      debugger; 
      var EmpData = GetAllEmployees(); 
      // I see the empdata as undefined 
     }); 
     //Once i come out from here i see the method console.log diplsaying the data 
    </script> 
</head> 
<body> 
    <div> 
    </div> 
</body> 
</html> 

기능은 그것이 성공의 함수 끝에서 호출 왜 데이터를 반환 할 수있다라고 일단이처럼 행동 않는 이유를 정말 혼란. 더 많은 계산이 이루어지면 함수의 결과가 실제로 필요합니다. 정말 이에 대한 도움을 주셔서 감사합니다!

미리 감사드립니다.

+0

안녕하세요, 네트워크 탭을 확인한 결과 웹 API에서 반환 된 데이터와 함께 요청을 받으셨습니까? –

+0

예 개발자 도구 – Kumee

+0

을 사용하여 IE에 들어오는 데이터를 볼 수 있으며 반환 된 데이터 유형은 무엇입니까? 당신은 json으로 응답을 설정합니까? 응답은 유효한 json입니까? –

답변

1

자바 스크립트는 asynchronous입니다. 즉, async (webapi 호출과 같은) 함수를 호출하면 JS 처리는 응답을 얻을 때까지 기다리지 않고 계속 진행 함을 의미합니다. 결국 서버가 응답 할 때 콜백 함수가 호출됩니다 (귀하의 경우 success 메소드). 그래서 EmpDataundefined입니다. 할 수있는 일은 GetAllEmployees에 콜백을 전달하거나, ES6을 사용할 수있는 경우 promises과 같은 것을 사용하는 것입니다.

콜백

이것을 고려하십시오 : 다음

function GetAllEmployees(cb) 
     { 
      jQuery.support.cors = true; 
      $.ajax({ 
       url: 'http://localhost:61883/APIService/api/Employee/GetAllEmployees',// service call 
       type: 'GET', 
       dataType: 'json', 
       success: function (data) 
       { 
        cb(null, data) 
       }, 
       error: function (error) { 
        cb(error, null) 
       } 
      }); 
     } 

과 :

$(document).ready(function() 
    { 
    GetAllEmployees(function(err, data){ 
     if(!err) { 
     //here you have access to your data. 
     } 
    }); 
    }); 

약속

마찬가지로, asynchr를 작성하는 약속을 사용할 수 있습니다 (onous) 코드를 동기 방식으로 사용한다. 이것을 고려해보십시오 :

function GetAllEmployees() { 
    return new Promise(function(resolve, reject){ 
     jQuery.support.cors = true; 
     $.ajax({ 
      url: 'http://localhost:61883/APIService/api/Employee/GetAllEmployees',// service call 
      type: 'GET', 
      dataType: 'json', 
      success: function (data) 
      { 
       resolve(data) 
      }, 
      error: function (error) { 
       reject(error) 
      } 
     }); 
    }); 
} 

GetAllEmployees().then(function(data){ 
    //here you have access to the data 
}).catch(function(err){ 
    //error occurred 
}) 

약속을 사용하려면 전체 브라우저 지원을 받으려면 코드를 번역해야합니다.

관련 문제