你可以看一下jQuery内部实现:
[code="java"]parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},[/code]
1、如果你有JSON parse 就用它来进行解析:[url]http://www.json.org/js.html[/url]
2、否则 (new Function("return " + data))();
这里注意data一定是字符串的,也就是说struts2传给前端的数据没有错,你要认识到这点;
eval函数是浏览器内置的,它可以编译和执行任何javascript代码,因此相对来说不太安全,因此jQuery没有使用的:
[quote]The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. [/quote]