在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博客'}; |
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')); |
|
下面用jQuery表单提交的案例来演示一下toJson和fromJson的用法:
toJson:将json对象转为json字符串;
fromJson:将json字符串转为json对象。
html和js部分:
04 | <meta charset="UTF-8"> |
05 | <title>Document</title> |
06 | <meta name="Keywords" content=""> |
07 | <meta name="Description" content=""> |
09 | <body ng-app="app" ng-controller="ctrl"> |
10 | <form action="./5.php" method="post"> |
13 | <input type="text" name="name" ng-model="blog.name" ng-value="blog.name" /> |
17 | <input type="text" name="url" ng-model="blog.url" ng-value="blog.url"/> |
19 | <input type="text" name="data" /> |
21 | <input type="submit" /> |
25 | <script type="text/javascript" src="../js/angular.min.js"></script> |
26 | <script type="text/javascript" src="http://www.zymseo.com/js/demo.js"></script> |
27 | <script 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)); |
|
php部分:
2 | header('Content-type:text/html;charset="utf-8"'); |
3 | var_dump(gettype($_POST['data'])); |
4 | var_dump(json_decode($_POST['data'], true)); |
|