2016-06-11 4 views
1

json 데이터가 비어 있는지 확인하고 싶습니다.JSON 데이터가 비어있는 경우 경고 - 코드가 작동하지 않습니다.

json이 비어 있으면 orders Not Found으로 알려주세요. 비어 있지 않은 경우 orders found으로 알려주십시오.

사용자가 로그인하지 않은 경우 로컬 저장소에 토큰이 없습니다. 브라우저가 API URL을 요청하면 500 오류가 발생합니다. 그럼 난 failed status reason

내 dev에 아프다, 그래서 내 자신을 시도하고 failed 경고하고 싶습니다. 그것도 잘 안가.

아래 코드를 사용해 보았습니다. 전혀 작동하지 않았습니다.

<script>    
$http.get("http://localhost.com/activeorders/?format=json",{ 
      headers: {'Authorization': 'Token '+ localStorage.getItem("token")}}) 
       .success(function(response) { 

        if(response=="[]") 
        { 

         alert(" orders NOT found"); 


        } 
        else 
        { 

         alert("orders found"); 
        } 

        .error(function(response,status) { 

     alert("failed"); 
    alert(status); 
       } 
       return ; 
      }); 

</script> 

도움이 될 것입니다. JS 객체 또는 JSON이 비어있는 경우 검사 할 경우

+1

빈 응답을 디버그하십시오. 데이터가 배열이어야하는 responsece.data와 같은 경우 배열 길이를 확인하십시오. 데이터가 객체 일 경우 - 제시된 자신의 속성을 확인하십시오 – Vitalii

+0

If (response.length === 0) –

+0

으로 확인하십시오. 응답 기록을 여기에 입력하십시오. 어쩌면 당신은 그것을 잘못 취급 할 수 있습니다. –

답변

2

시도 Angular js 인 경우 콜백 :

을 사용하여 아래 코드를 시도 할 수 있습니다. (210)
$http({ 
     method: 'GET', 
     url: 'http://localhost.com/activeorders/?format=json', 
     headers: { 
      'Authorization': 'Token '+ localStorage.getItem('token') 
     } 
    }).then(function successCallback(response){ // this callback will be called asynchronously when the response is available 
      if (response.data.length == 0){ 
       console.log("orders NOT found") 
      } 
     // or if you just return an array json by php for example 
      //if (response.length == 0) { 
       //console.log("orders NOT found") 
      //}   
     }, function errorCallback(response){ // called asynchronously if an error occurs or server returns response with an error status. 
      if (response){ 
      alert("failed"); 
      } 
     }); 

외부 파일 .json 유형을 사용하는 경우, 당신은 시도 할 수 있습니다 :

menuApp.controller("dynamicMenuController", function($scope, $http) { 
$http.get('config/menu.json').success(function(data) { 
    console.log("success!"); 
    if(data.length == 0){ 
     alert('empty'); 
    } 
    else {alert('some here!')} 
}); 

당신의 JSON은 다른 도메인, 외부 도메인에있는 경우. 이 경우 대신 JSONP을 살펴 보시길 바랍니다. http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/consuming-jsonp-apis.html :

$http.jsonp('http://teckstack.com/api/get_recent_posts/?callback=JSON_CALLBACK').success(function (data) { 
    console.log("success callback"); 
    if(data.length == 0){ 
     alert('empty'); 
    } // response data 
}).error(function (data) { 
    console.log("failed callback"); 
}); 
+0

** 웹 서비스 메소드가 올바른 헤더를 가진 json을 반환하는지 ** 확인해야합니다 ** –

+0

감사합니다.하지만 작동하지 않는 것 같습니다. : //pastebin.com/2uvePTsn –

1

({})는, 예를 들어, 객체는 response입니다 : 당신이하려고하는 경우
Object.keys(response).length === 0 && response.constructor === Object

0

if(Object.keys(JSON.parse(response)).length == 0){ 
    alert("err") 
} 
+0

@ Radolf, 작동하지 않습니다! : –

+0

그것의 response.data.lenght –

+0

@ TirthrajBarot, http://pastebin.com/2uvePTsn –

관련 문제