日期:2014-05-16  浏览次数:20374 次

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() 快很多倍
/**