我想检查json数据是否为空
如果 json 为空,我想提醒 Orders Not Found
。
如果它不为空,我想提醒 找到订单
。
如果用户没有登录,他的本地存储中不会有任何 token 。所以当浏览器请求 API URL 时他会得到 500 错误。然后我想提醒 failed
以及 failed status reason
我的开发者病了,所以自己试了一下。它不太顺利。
尝试了下面的代码,根本不起作用。
<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>
任何帮助将不胜感激。
最佳答案
如果你想在 Angular js 中做,那么你可以使用回调尝试下面的代码:
$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");
});
关于javascript - 如果 JSON 数据为空则发出警报 - 代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37761835/