angular.toJson 是把一个对象转换成Json字符串。
angular.fromJson是从一个Json字符串解析出一个对象或者对象数组。
例如:
if($rootScope.loginData == null && $rootScope.rolesList == null){
$.ajax({
url: config.loginUrl, type: "POST", dataType: "json", cache: false, async: false,
xhrFields: {
withCredentials: true
},
data: null,
success: function (data) {
if(data && angular.fromJson(data.data).access_token != null){
//此处的$rootScope.loginData充当定义对象的作用,必须使用fromJson,使用toJson则会报错。
$rootScope.loginData = angular.fromJson(data.data);
//设置cookie值的时候,需要字符串,而不是对象,所有使用toJson
setCookie('loginDate',angular.toJson($rootScope.loginData), 0);
$.ajax({
url: config.userInfoUrl + "?userCode=" + ($rootScope.loginData.userCode), type: "GET", dataType: "json", cache: false, async: false,
xhrFields: {
withCredentials: true
},
beforeSend: function(request) {
//request.setRequestHeader();
},
data: null,
success: function (userInfo) {
angular.extend($rootScope.loginData, userInfo);
setCookie('loginDate',angular.toJson($rootScope.loginData), 0);
$.ajax({
url: config.userGradeInfo +"/"+ $rootScope.loginData.userCode, type: "GET", dataType: "json", cache: false, async: false,
xhrFields: {
withCredentials: true
},
beforeSend: function(request) {
//request.setRequestHeader();
},
data: null,
success: function (userGrades) {
$rootScope.rolesList = userGrades.data;
var postData = angular.copy($rootScope.loginData);
angular.extend(postData, userGrades.data);
setCookie('rolesList',angular.toJson($rootScope.rolesList), 0);
},
error: function (status) {
setCookie('loginDate',"");
messageBox.alert("请刷新重试", "error");
$timeout(function(){
window.location.reload();
}, 5000);
}
});
},
error: function (status) {
setCookie('loginDate',"");
messageBox.alert("获取用户信息出错,请刷新重试", "error");
$timeout(function(){
window.location.reload();
}, 5000);
}
});
}
else{
messageBox.alert("验证登录信息失败:access_token为空,点击确定重新登录")
}
},
error: function (status) {
console.log(status);
}
});
}