jQuery发送含有数组参数的ajax请求以及后台Struts2的OGNL解析错误
當(dāng)使用jquery1.3以上版本時(shí),進(jìn)行ajax參數(shù)傳值時(shí),會出現(xiàn)以下的一個(gè)錯(cuò)誤:?
ognl.ExpressionSyntaxException: Malformed OGNL expression: f[] [ognl.ParseException: Encountered " "]"
"] "" at line 1, column 3. 這個(gè)錯(cuò)誤是因?yàn)?jquery在傳遞數(shù)組類參數(shù)時(shí),將不再遵循1.3時(shí)如f=x&f=y的參數(shù)傳遞了,而是采用了像php一樣,帶中括號的參數(shù)傳遞。js值 {f:["x","y"]},將被轉(zhuǎn)化成f[]=x&f[]=y,而這種參數(shù)形式傳遞到后臺時(shí),使用struts2.1.8版本時(shí),就會出現(xiàn)以上的錯(cuò)誤形式。?
??? struts2一直能夠識別的模式僅是f=x&f=y這樣,當(dāng)后臺聲明f為一個(gè)list或set時(shí),就會把x,y分別加入到list或set中。而如果是f[]這種形式,則會報(bào)相應(yīng)的轉(zhuǎn)換錯(cuò)誤。?
??? 解決此問題的方法很簡單,在進(jìn)行ajax請求時(shí),追加一條以下語句即可:?
$.ajaxSettings.traditional=true; 這是一個(gè)全局參數(shù),故可以在引入jquery.js之后進(jìn)行聲明。此參數(shù)的意思在于,使用$.param時(shí),將采用舊的jquery1.3版本的param生成方式進(jìn)行處理。?
具體的區(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 超屏加载