1. 程式人生 > >ajax表單提交使用serialize()方法解決中文亂碼

ajax表單提交使用serialize()方法解決中文亂碼

         最近做了一個暫存功能,需要無重新整理的表單提交,然後我用ajax的表單提交。在使用ajax提交form值的時候,需要使用serialize()去獲取form的值。但是在這樣獲取過程中,中文就會產生亂碼。serialize() 方法通過序列化表單值,建立 URL 編碼文字字串。可以選擇一個或多個表單元素(比如 input 及/或 文字框),或者 form 元素本身。序列化的值可在生成 AJAX 請求時用於 URL 查詢字串中。由於做的這個form表單要提交的內容比較多,所以用前段編碼,後臺解碼的方式。

       前段程式碼

      encodeURI(encodeURI(data)) ///注意兩次編碼!!

              後臺程式碼

response.setCharacterEncoding("UTF-8");	//response.setContentType("text/html;charset=UTF-8"); //用於向頁面輸送中文字串 java.net.URLDecoder.decode((String)request.getParameter("username"),"UTF-8");
           不適用這麼做要累死人。那麼就從重寫jquery編碼的方式考慮。
function doSubmit(){
    $.ajax({
            type: "POST",
            url:"XXX.do",    
            data:$('#form').serialize(),
            error: function(request) {
            alert("傳送請求失敗!");
            },
             success: function(data) {

             }
        });   
    }

重寫jquery編碼的方法

jQuery.param=function( a ) {  
    var s = [ ];  
    var encode=function(str){  
        str=escape(str);  
        str=str.replace(/%20/g,"%u002B");  
        return str;  
    };  
    function add( key, value ){  
        s[ s.length ] = encode(key) + '=' + encode(value);  
    };  
    // If an array was passed in, assume that it is an array  
    // of form elements  
    if ( jQuery.isArray(a) || a.jquery )  
        // Serialize the form elements  
        jQuery.each( a, function(){  
            add( this.name, this.value );  
        });  

    // Otherwise, assume that it's an object of key/value pairs  
    else  
        // Serialize the key/values  
        for ( var j in a )  
            // If the value is an array then the key names need to be repeated  
            if ( jQuery.isArray(a[j]) )  
                jQuery.each( a[j], function(){  
                    add( j, this );  
                });  
            else  
                add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );  

    // Return the resulting serialization  
    return s.join("&").replace(/%20/g, "+");  
}  
也可以把上段程式碼封裝個js方便呼叫