当前位置: 代码迷 >> JavaScript >> js操作cookie,将字符串数据解析替json格式
  详细解决方案

js操作cookie,将字符串数据解析替json格式

热度:404   发布时间:2012-12-14 10:33:08.0
js操作cookie,将字符串数据解析为json格式
function trim(str){		//删除左右两端的空格			
	return str.replace(/(^\s*)|(\s*$)/g, "");
}
	
function setCookie(sName, sValue, days) { //写cookies函数
	var expires = new Date();
	expires.setTime(expires.getTime() + parseInt(days) * 24 * 60 * 60 * 1000);
	document.cookie = sName + "=" + escape(sValue) + ";expires=" + expires.toGMTString()+";path=/;domain=xxx.cn";
};
     
function getCookie(name){ //取cookies函数	 
	var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
	if(arr != null) return unescape(arr[2]); return null;
}
	 
function parseJSON(data){
	if ( typeof data !== "string" || !data ) {
		return null;
	}
	// Make sure leading/trailing whitespace is removed (IE can't handle it)
	data = jQuery.trim(data);
	// Attempt to parse using the native JSON parser first
	if ( window.JSON && window.JSON.parse ) {
		return window.JSON.parse(data);
	}
	// Make sure the incoming data is actual JSON
	// Logic borrowed from http://json.org/json2.js
	if ( rvalidchars.test( data.replace( rvalidescape, "@" )
		.replace( rvalidtokens, "]" )
		.replace( rvalidbraces, "")) ) {
		return ( new Function( "return " + data ) )();
	}
	OpPopAlert( "Invalid JSON: " + data );
	return;
}	

其中:

if ( window.JSON && window.JSON.parse ) {
		return window.JSON.parse(data);
	}
将javascript 中字符串数据转换为 json 对象有三种方法:
1. eval() 函数
2. 使用 new Function() 构造函数
3. 使用浏览器内置的JSON.parse 方法(IE Version > IE8(s))
下面来说说使用这三种方法的建议:

eval() 函数,很强大的函数,会模拟一个js 解析器,能解析任何js 代码,但是执行效率和安全性不是很高好,所能在做demo时候可以使用,但是在做项目是不推荐使用。

Function 构造函数方法,这是Jquery 中解析JSON数据的方法,查看他的源代码中即可看到,使用此方法,经人测试,比eval() 快很多倍
/**
*jQuery源码分析,557-580行
*creator liangqi
*Date 2011-12-3
*Email liangqi000#gmail.com
 */
... ...
parseJSON: function(data ){
if(typeof(data) !== 'string' || !data ){
return null;
}

if(window.JSON && window.JSON.parse){
return window.JSON.parse(data);
}
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {

     return (new Function( "return " + data ))();
   
  }
 jQuery.error( "Invalid JSON: " + data );
}

三种使用方法:
var json = '{"name":"liangqi"; "sex":"boy"}';
jsonObj0 = eval('(' + json + ')');
jsonObj1 = (new Function('return' + json))();
if(window.JSON){
jsonObj2 = JSON.parse(json);
} else {
... ... //针对比支持此方法的调用此处
}

  相关解决方案