jQuery Ajax提交表單亂碼問題的解決

同事請求幫忙,說程序好好的,突然就在提交表單的時候亂碼了。本着助人爲樂的精神,去看了一下。瞭解了一下狀況後開始調試。 發現請求提交到後臺的時候中文已經變成了亂碼。檢查web.xml, 發現有編碼轉換的Filter, 檢查頁面,編碼是UTF-8,檢查request的編碼,也是UTF-8,編碼都是一致的。就是提交到後臺的時候亂碼。 試着把取到的亂碼進行轉碼,發現以下的狀況能夠正常得到中文:java

<!-- lang: java -->
new String(name.getBytes("iso-8850-1"), "utf-8")

接近崩潰的邊緣了。再查Post到後臺的數據,中文也是UTF-8的編碼。web

開始百度,有人說在jQuery中設置ajaxSettings的contentType屬性,在後面加上";charset=utf-8"ajax

<!-- lang: js -->
ajaxSettings: {
	url: ajaxLocation,
	isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
	global: true,
	type: "GET",
	contentType: "application/x-www-form-urlencoded;charset=utf-8",
	processData: true,
	async: true,
            ......
  }

試着改了以後,發現果真能夠解決問題。app

可是總以爲這麼解決問題有點怪怪的,jQuery那麼多人用,爲啥非要指定這個utf-8的編碼呢,若是項目用的不是utf-8呢? 回到本身的位子繼續研究。項目中用的是Spring的CharacterEncodingFilter, 懶得下源碼,因而本身寫了個EncodingFilter加在前面,發現request.getCharacterEncoding()返回的是null,因而手動設置了一下編碼爲utf-8, 再getParameter, 發現是正常的中文。async

此處省去部分文字……ide

在javaEE的文檔裏,對於setCharacterEncoding的解釋是這樣的:this

<!-- lang: java -->
Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader(). Otherwise, it has no effect.

最後發現是Filter的順序問題致使。在encodingFilter以前配置了其餘的Filter,恰好在那裏調用了get方法,調整以後,一切恢復正常。編碼

相關文章
相關標籤/搜索