首页 > 代码库 > josn化表单数据

josn化表单数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
 * josn化表单数据
 * @name baidu.form.json
 * @function
 * @grammar baidu.form.json(form[, replacer])
 * @param {HTMLFormElement} form        需要提交的表单元素
 * @param {Function} replacer           对参数值特殊处理的函数,replacer(string value, string key)
                
 * @returns {data} 表单数据js对象
 */
form.json = form.json || function (form, replacer) {
    var elements = form.elements,
        replacer = replacer || function (value, name) {
            return value;
        },
        data = http://www.mamicode.com/{},
        item, itemType, itemName, itemValue,
        opts, oi, oLen, oItem;
         
    /**
     * 向缓冲区添加参数数据
     * @private
     */
    function addData(name, value) {
        var val = data[name];
        if(val){
            val.push || ( data[name] = [val] );
            data[name].push(value);
        }else{
            data[name] = value;
        }
    }
     
    for (var i = 0, len = elements.length; i < len; i++) {
        item = elements[i];
        itemName = item.name;
         
        // 处理:可用并包含表单name的表单项
        if (!item.disabled && itemName) {
            itemType = item.type;
            itemValue = http://www.mamicode.com/baidu.url.escapeSymbol(item.value);
 
            switch (itemType) {
            // radio和checkbox被选中时,拼装queryString数据
            case ‘radio‘:
            case ‘checkbox‘:
                if (!item.checked) {
                    break;
                }
                 
            // 默认类型,拼装queryString数据
            case ‘textarea‘:
            case ‘text‘:
            case ‘password‘:
            case ‘hidden‘:
            case ‘file‘:
            case ‘select-one‘:
                addData(itemName, replacer(itemValue, itemName));
                break;
                 
            // 多行选中select,拼装所有选中的数据
            case ‘select-multiple‘:
                opts = item.options;
                oLen = opts.length;
                for (oi = 0; oi < oLen; oi++) {
                    oItem = opts[oi];
                    if (oItem.selected) {
                        addData(itemName, replacer(oItem.value, itemName));
                    }
                }
                break;
            }
        }
    }
 
    return data;
};