javascript - Alert if JSON Data is Empty - Code not working -
i want check if json data empty or not.
if json empty, want alert orders not found
. if not empty, want alert orders found
.
if user not logged in, there won't token in localstorage. 500 error when browser requests api url. want alert failed
along failed status reason
my dev sick, tried self. not going well.
tried below code, not @ working.
<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>
any thankfull.
if trying in angular js, can try code below using callbacks:
$http({ method: 'get', url: 'http://localhost.com/activeorders/?format=json', headers: { 'authorization': 'token '+ localstorage.getitem('token') } }).then(function successcallback(response){ // callback called asynchronously when response available if (response.data.length == 0){ console.log("orders not found") } // or if return array json php example //if (response.length == 0) { //console.log("orders not found") //} }, function errorcallback(response){ // called asynchronously if error occurs or server returns response error status. if (response){ alert("failed"); } });
if using external file .json type, can try :
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!')} });
if json in domain, external domain . in case , suggest @ jsonp instead, here's example 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"); });
Comments
Post a Comment