您好我从服务器
收到以下回复{
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
}
我需要根据状态显示消息,我们正在使用角度和JavaScript我无法循环阅读相同,任何帮助将不胜感激
答案 0 :(得分:1)
您可以通过将字符串解析为json:
来读取值var obj = JSON.parse('{"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}}')
然后您可以访问属性值
obj.Application1.status
答案 1 :(得分:1)
我能想象的最简单的版本:
<script>
var json = {"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}};
for(var t in json)
console.log(json[t]['status']);
</script>
答案 2 :(得分:0)
首先检查响应是JSON对象还是字符串。如果是字符串,则将其解析为JSON。然后你可以循环它。
使用以下功能
isJson(your_response);
将返回JSON对象或null。
var whatIsIt = function (object) {
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = {}.constructor;
if (object === null) {
return "null";
}
else if (object === undefined) {
return "undefined";
}
else if (object.constructor === stringConstructor) {
return "String";
}
else if (object.constructor === arrayConstructor) {
return "Array";
}
else if (object.constructor === objectConstructor) {
return "Object";
}
else {
return "don't know";
}
};
var isJson = function(o1)
{
// Validate JSON strings
var json_object = null;
var type = whatIsIt(o1);
switch(type)
{
case "String":
try{
json_object = JSON.parse(o1);
}catch (e){
return null;
}
break;
case "Object":
try {
JSON.stringify(o1);
json_object = o1;
}catch (e) {
return null;
}
break;
}
return json_object;
};
答案 3 :(得分:0)
假设与服务器的通信是在单独的角度服务中执行的,则需要使用ng-repeat和ng-if指令, 请在这里找到JSFiddle: http://jsfiddle.net/2ju3c6tc/1/
var module = angular.module("myModule", []);
module.service('serverCommunicator', ['$http',
function($http) {
//code to get the data from the server
//server Data would hold the JSON object after the AJAX req,however, it is assigned manually over here
this.serverData = {
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
};
}
]);
module.controller('myController', ['$scope', 'serverCommunicator',
function($scope, serverCommunicator) {
$scope.serverData = serverCommunicator.serverData;
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController as myCont">
<div ng-repeat="dataElement in serverData">
<div ng-if="dataElement.status=='SUCCESS'">
This is success message :{{dataElement.comment}}
</div>
<div ng-if="dataElement.status=='FAILURE'">
This is failure message {{dataElement.comment}}
</div>
</div>
</div>
</div>