1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误

jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误

时间:2019-11-11 07:10:43

相关推荐

jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误

当使用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// objectif ( 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 );}}

转自/index.php/code/10110001.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。