close

最近遇到一個問題, 於JSP中使用 Jeditable (demo)套件, 輸入完中文以 Jeditable 內的

ajax 方式將輸入中文內容送至後端 Servlet 再更新至 MySQL ,  同一頁面以 FireFox 操作時

順利更新至 DB,  以 IE 操作時更新至 DB 的中文欄位內容都會變成亂碼...

 

本以為在 Jsp 中的 JQuery 設定了以 POST 送至 Servlet 可以較確中文不變成亂碼,

但實際上沒有差別, google 了一些資料, 以及 Jeditable 下相關的留言中發看到一段文字是這麼提的:

Accordingly with jQuery documentation, "POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard". So trying to set the contentType (jQuery ajax option) on the ajaxoptions jeditable paremeter will have no effect. You'll have to deal with the UTF-8 data server-side, which is easy if you're using PHP with the utf8_decode() function.

於是看起來, 在 JQuery 中設置的 contentType(

contentType: "application/json; charset=UTF-8",

)對 ajaxoptions jeditable paremeter 沒有任何效果。比較理想的方式是在 Server 端處理 UTF-8 的資料。

 

於是於 Servlet 中寫成

String op = request.getParameter("op");
op = new String(op.getBytes("iso-8859-1"),"utf-8");


改成這種寫法, 後端 Servlet 收到以 IE 操作的 Jeditable 頁面所 submit 的中文
都正常無誤, 但原先以 FF submit 過來的內容則因為多了 getBytes 轉碼處理反而
變成亂碼。很明顯這個寫法在此並不理想...


最後在servlet改成以
request.setCharacterEncoding("UTF-8");
(但前提是jsp中使用POST傳送)即可順利收到
request.getParameter("op")內的中文字串,
也不用再額外用getBytes()再作一次轉碼。

arrow
arrow
    全站熱搜

    ness 發表在 痞客邦 留言(1) 人氣()