jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误
當(dāng)使用jquery1.3以上版本時,進行ajax參數(shù)傳值時,會出現(xiàn)以下的一個錯誤:?
ognl.ExpressionSyntaxException: Malformed OGNL expression: f[] [ognl.ParseException: Encountered " "]"
"] "" at line 1, column 3. 這個錯誤是因為,jquery在傳遞數(shù)組類參數(shù)時,將不再遵循1.3時如f=x&f=y的參數(shù)傳遞了,而是采用了像php一樣,帶中括號的參數(shù)傳遞。js值 {f:["x","y"]},將被轉(zhuǎn)化成f[]=x&f[]=y,而這種參數(shù)形式傳遞到后臺時,使用struts2.1.8版本時,就會出現(xiàn)以上的錯誤形式。?
??? struts2一直能夠識別的模式僅是f=x&f=y這樣,當(dāng)后臺聲明f為一個list或set時,就會把x,y分別加入到list或set中。而如果是f[]這種形式,則會報相應(yīng)的轉(zhuǎn)換錯誤。?
??? 解決此問題的方法很簡單,在進行ajax請求時,追加一條以下語句即可:?
$.ajaxSettings.traditional=true; 這是一個全局參數(shù),故可以在引入jquery.js之后進行聲明。此參數(shù)的意思在于,使用$.param時,將采用舊的jquery1.3版本的param生成方式進行處理。?
具體的區(qū)別代碼如下所示:?
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 );} }
轉(zhuǎn)自http://www.iflym.com/index.php/code/201110110001.html
轉(zhuǎn)載于:https://www.cnblogs.com/hyqs/articles/3910383.html
總結(jié)
以上是生活随笔為你收集整理的jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开办养老院需要多少钱?
- 下一篇: jQuery 超屏加载