读书人

解决施用jquery1.3以上版本时出现Malf

发布时间: 2013-03-27 11:22:42 作者: rapoo

解决使用jquery1.3以上版本时出现Malformed OGNL expression: f[] [ognl.ParseException: Encount
当使用jquery1.3以上版本时,进行ajax参数传值时,会出现以下的一个错误:

ognl.ExpressionSyntaxException: Malformed OGNL expression: f[] [ognl.ParseException: Encountered " "]" "] "" at line 1, column 3.

这个错误是因为,jquery在传递数组类参数时,将不再遵循1.3时如f=x&f=y的参数传递了,而是采用了像php一样,带中括号的参数传递。js值 {f:["x","y"]},将被转化成f[]=x&f[]=y,而这种参数形式传递到后台时,使用struts2.1.8版本时,就会出现以上的错误形式。

struts2一直能够识别的模式仅是f=x&f=y这样,当后台声明f为一个list或set时,就会把x,y分别加入到list或set中。而如果是f[]这种形式,则会报相应的转换错误。

解决此问题的方法很简单,在进行ajax请求时,追加一条以下语句即可:
$.ajaxSettings.traditional=true;


这是一个全局参数,故可以在引入jquery.js之后进行声明。此参数的意思在于,使用$.param时,将采用旧的jquery1.3版本的param生成方式进行处理。
具体的区别代码如下所示:
function buildParams( prefix, obj, traditional, add ) {    if ( jQuery.isArray( obj ) && obj.length ) {        // Serialize array item.        jQuery.each( obj, function( i, v ) {            if ( traditional || rbracket.test( prefix ) ) {                // Treat each array item as a scalar.                add( prefix, v );             } else {                // If array item is non-scalar (array or object), encode its                // numeric index to resolve deserialization ambiguity issues.                // Note that rack (as of 1.0.0) can't currently deserialize                // nested arrays properly, and attempting to do so may cause                // a server error. Possible fixes are to modify rack's                // deserialization algorithm or to provide an option or flag                // to force array serialization to be shallow.                buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );            }        });     } else if ( !traditional && obj != null && typeof obj === "object" ) {        // If we see an array here, it is empty and should be treated as an empty        // object        if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {            add( prefix, "" );         // Serialize object item.        } else {            for ( var name in obj ) {                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );            }        }     } else {        // Serialize scalar item.        add( prefix, obj );    }}

转自http://www.iflym.com/index.php/code/201110110001.html

读书人网 >Web前端

热点推荐