AngularJs将json字符串转为对象fromJson和将对象转为json字符串toJson

在AngularJs中,json形式的字符串可以转为json格式的对象,代码如下:

利用HTML5的2种本地存储方式(localStorage和sessionStorage)来做测试:

01 var m = angular.module('app', []);
02 m.controller('ctrl', ['$scope'function($scope){
03     $scope.data = {'name':'K`illCode博客'};
04     //window.localStorage.setItem('data', $scope.data);
05     //console.log(window.localStorage.getItem('data'));
06      
07     window.sessionStorage.setItem('data', angular.toJson($scope.data));
08     console.log(angular.fromJson(window.sessionStorage.getItem('data')));
09     console.log(window.sessionStorage.getItem('data'));
10 }]);

下面用jQuery表单提交的案例来演示一下toJson和fromJson的用法:

toJson:将json对象转为json字符串;

fromJson:将json字符串转为json对象。

html和js部分:

01
02 "en">
03     <head>
04         "UTF-8">
05         Document
06         "Keywords" content="">
07         "Description" content="">
08     head>
09     "app" ng-controller="ctrl">
10         
"./5.php" method="post">
11             

12                 
13                 type="text" name="name" ng-model="blog.name" ng-value="blog.name" />
14             

15             

16                 
17                 type="text" name="url" ng-model="blog.url" ng-value="blog.url"/>
18             

19             type="text" name="data" />
20             {{blog.name}}
21             type="submit" />
22         
23     
24
25 type="text/javascript" src="../js/angular.min.js">
26 type="text/javascript" src="http://www.zymseo.com/js/demo.js">
27 type="text/javascript">
28 var m = angular.module('app', []);
29 m.controller('ctrl', ['$scope'function($scope){
30     $scope.blog = {'name':'K`illCode技术博客''url':'http://blog.csdn.net/dome_'};
31     $('form').submit(function(){
32         if($scope.blog.name!='' && $scope.blog.url!=''){
33             $('[name="data"]').val(angular.toJson($scope.blog));
34         }
35     });
36 }]);
37

php部分:

1
2     header('Content-type:text/html;charset="utf-8"');
3     var_dump(gettype($_POST['data']));//string
4     var_dump(json_decode($_POST['data'], true));//array

你可能感兴趣的:(angularJS)