欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJs将json字符串转为对象fromJson和将对象转为json字符串toJson(代码教程)

程序员文章站 2022-04-24 17:57:42
在AngularJs中,json形式的字符串可以转为json格式的对象,代码如下: 利用HTML5的2种本地存储方式(localStorage和sessionStorage)来做...

在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	<!doctype html>
02	<html lang="en">
03	    <head>
04	        <meta charset="UTF-8">
05	        <title>Document</title>
06	        <meta name="Keywords" content="">
07	        <meta name="Description" content="">
08	    </head>
09	    <body ng-app="app" ng-controller="ctrl">
10	        <form action="./5.php" method="post">
11	            <p>
12	                <label>博客名称:</label>
13	                <input type="text" name="name" ng-model="blog.name" ng-value="blog.name" />
14	            </p>
15	            <p>
16	                <label>博客地址:</label>
17	                <input type="text" name="url" ng-model="blog.url" ng-value="blog.url"/>
18	            </p>
19	            <input type="text" name="data" />
20	            {{blog.name}}
21	            <input type="submit" />
22	        </form>
23	    </body>
24	</html>
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));
34	        }
35	    });
36	}]);
37	</script>

php部分:

1	<?php
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