error : 自定义错误
parseJSON : 字符串转json
trim : 去除字符串头尾空字符
parseJSON方法先判断参数是否为字符串,否则返回空对象,再去除字符串头尾空字符,判断是否支持window.JSON.parse,否则使用json2.js中的方法。
var core_trim = String.prototype.trim, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g, // JSON RegExp rvalidchars = /^[],:{}s]*$/, rvalidbraces = /(?:^|:|,)(?:s*[)+/g, rvalidescape = /\(?:["\/bfnrt]|u[da-fA-F]{4})/g, rvalidtokens = /"[^"\ ]*"|true|false|null|-?(?:dd*.|)d+(?:[eE][-+]?d+|)/g; jQuery.extend({ ...................... error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { 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 ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("uFEFFxA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, ............... });