日期:2014-05-16 浏览次数:20409 次
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 对象有三种方法: