原生JS實現表單序列化serialize()


有一個form表單,要用AJAX后台提交,原來想拼接json,但是數據多了麻煩,不靈活。

 用HTML5的FormData來初始化表單

var formdata=new FormData(document.getElementById("advForm"));

看似還可以,但發現有兩個問題,

一,formdata.get()方法不知為什么用不了

二,Form Data 數據格式不如Jq的簡潔,

WebKitFormBoundary29h06FRZequJgQtR
        var stu={
            name:"冷榮富",
            age:22,
            sex:"男"
        };
        $.ajax({
            type : "POST",  //提交方式
            url : "http://localhost/jsonTest.php",//路徑,www根目錄下
            data : {
                "student" : stu
            },//數據,這里使用的是Json格式進行傳輸
            success : function(result) {//返回數據根據結果進行相應的處理
                alert(result);
            }
        });

這段JQ提交的數據是序列化的

網查如然不用我造輪子了,轉一個可用的

使用原生的js模擬了表單序列化,代碼中對表單處理盡可能地進行文字說明 
其中對於url,字段名稱,中文進行了使用了encodeURIComponent()進行編碼。

Object.prototype.serialize = function(){
    var res = [],   //存放結果的數組
        current = null, //當前循環內的表單控件
        i,  //表單NodeList的索引
        len, //表單NodeList的長度
        k,  //select遍歷索引
        optionLen,  //select遍歷索引
        option, //select循環體內option
        optionValue,    //select的value
        form = this;    //用form變量拿到當前的表單,易於辨識

    for(i=0, len=form.elements.length; i<len; i++){

        current = form.elements[i];

        //disabled表示字段禁用,需要區分與readonly的區別
        if(current.disabled) continue;

        switch(current.type){
            //可忽略控件處理
            case "file":    //文件輸入類型
            case "submit":  //提交按鈕
            case "button":  //一般按鈕
            case "image":   //圖像形式的提交按鈕
            case "reset":   //重置按鈕
            case undefined: //未定義
                break;
            //select控件
            case "select-one":
            case "select-multiple":
                if(current.name && current.name.length){
                    console.log(current)
                    for(k=0, optionLen=current.options.length; k<optionLen; k++){
                        option = current.options[k];
                        optionValue = "";
                        if(option.selected){
                            if(option.hasAttribute){
                                optionValue = option.hasAttribute('value') ? option.value : option.text
                            }else{
                                //低版本IE需要使用特性 的specified屬性,檢測是否已規定某個屬性
                                optionValue = option.attributes('value').specified ? option.value : option.text;    
                            }
                        }
                        res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(optionValue));
                    }
                }
                break;

            //單選,復選框
            case "radio":
            case "checkbox":
                //這里有個取巧 的寫法,這里的判斷是跟下面的default相互對應。
                //如果放在其他地方,則需要額外的判斷取值
                if(!current.checked) break;

            default:
                //一般表單控件處理
                if(current.name && current.name.length){
                    res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(current.value));
                }
        }
    }
    return res.join("&");
}

對HTML表單使用:

formElement.serialize();

得到類似如下結果:a=1&b=2&c=3&d=4&e=5

相關鏈接:https://blog.csdn.net/qq_35087256/article/details/81253559


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM