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

阅读() @2018-10-29 18:16:09

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

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

var m = angular.module('app', []);
m.controller('ctrl', ['$scope', function($scope){
	$scope.data = {'name':'赵一鸣博客'};
	//window.localStorage.setItem('data', $scope.data);
	//console.log(window.localStorage.getItem('data'));
	
	window.sessionStorage.setItem('data', angular.toJson($scope.data));
	console.log(angular.fromJson(window.sessionStorage.getItem('data')));
	console.log(window.sessionStorage.getItem('data'));
}]);

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

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

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

html和js部分:

<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<meta name="Keywords" content="">
		<meta name="Description" content="">
	</head>
	<body ng-app="app" ng-controller="ctrl">
		<form action="./5.php" method="post">
			<p>
				<label>博客名称:</label>
				<input type="text" name="name" ng-model="blog.name" ng-value="blog.name" />
			</p>
			<p>
				<label>博客地址:</label>
				<input type="text" name="url" ng-model="blog.url" ng-value="blog.url" />
			</p>
			<input type="text" name="data" />
			{{blog.name}}
			<input type="submit" />
		</form>
	</body>
</html>
<script type="text/javascript" src="../js/angular.min.js"></script>
<script type="text/javascript" src="http://www.zymseo.com/js/demo.js"></script>
<script type="text/javascript">
var m = angular.module('app', []);
m.controller('ctrl', ['$scope', function($scope){
	$scope.blog = {'name':'赵一鸣技术博客', 'url':'http://www.zymseo.com'};
	$('form').submit(function(){
		if($scope.blog.name!='' && $scope.blog.url!=''){
			$('[name="data"]').val(angular.toJson($scope.blog));
		}
	});
}]);
</script>

php部分:

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

(完)!

微信二维码