首页 > 试题广场 >

编写一个函数实现form的序列化(即将一个表单中的键值序列化

[问答题]
编写一个函数实现form的序列化(即将一个表单中的键值序列化为可提交的字符串)



<!-- 表单数据 --> <form id="target"> <select name="age"> <option value="aaa">aaa</option> <option value="bbb" selected>bbb</option> </select> <input name="name" value="qiudeqing"> <input type="password" name="password" value="11111"> <input type="hidden" name="salery" value="3333"> <textarea name="description">description</textarea> <input type="checkbox" name="hobby" value="football" checked>Football <input type="checkbox" name="hobby" value="basketball">Basketball <input type="radio" name="sex" value="Female" checked>Female <input type="radio" name="sex" value="Male">Male </form>
//表单序列化通用函数
function serialize(form){
    var parts = [],
        field = null, 
        i, j, len, optLen, option, optValue;

    for(i=0, len=form.elements.length; i<len; i++){
        field = form.elements[i];
        switch(field.type){
            case "select-one":       //单选框
            case "select-multiple":  //多选框
            if(field.name.length){
                for(j=0, optLen = field.options.length; j<optLen; j++){
                    option = field.options[j];
                    if(option.selected){
                        optValue = '';
                        if(option.hasAttribute){
                            optValue = (option.hasAttribute('value') ? option.value : option.text);  //非IE
                        }else{
                            optValue = (option.attributes['value'].specified ? option.value : option.text); //IE
                        }
                        parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(optValue));
                    }
                }
            }
            break;

            case undefined:  //字段集
            case "file":     //文件输入
            case "submit":   //提交按钮
            case "reset":    //重置按钮
            case "button":   //自定义按钮
            break;

            case "radio":    //单选按钮
            case "checkbox":  //复选按钮
                if(!field.checked){
                    break;
                }

            default:
            //不包含没有名字的表单字段
            if(field.name.length){
                parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
            }
        }
    }
    return parts.join("&"); //查寻字符串格式输出
}
//页面加载完成调用表单序列化函数(一般是提交按钮,这里只看效果)
window.onload = function(){
    var form = document.getElementById('target');
    console.log(serialize(form));
};
思路:js高程 14.4表单序列化
(1)对表单字段的name和value进行URL编码,使用&号分割
(2)不发送禁用的表单字段
(3)只发送勾选的复选框checkbox和单选按钮radio
(4)不发送type为reset和button的按钮
(5)多选选择框中每个选中的值单独一个条目
(6)在单击提交按钮提交表单的情况下,也会发送提交按钮;否则不发送提交按钮
(7)<select>元素的值,就是选中的<option>元素的value特性的值。如果没有value特性,则选择元素的文本值。
编辑于 2017-08-09 20:43:01 回复(0)
function serializeForm(form){
	if(!form||form.tagName.toUpperCase()!='FORM'){
		return false;
	}
	var res=[];
	var tag,tagType,tagVal,tagName;
	for(var i=0;i<form.length;i++){
		tag=form[i];
		tagType=form[i].type;
		tagVal=form[i].value;
		tagName=form[i].name;	
		var reg1=/['textArea'|'text'|'passsword']/g;
		var reg2=/['radio'|'checkbox']/g;
		var reg3=/['select']/g;
	    if(reg1.test(tagType)){
	    	res.push(encodeURIComponent(tagName)+"="+encodeURIComponent(tagVal));
	    }else if(reg2.test(tagType)&&tag.checked){
	    	res.push(encodeURIComponent(tagName)+"="+encodeURIComponent(tagVal));    
	    }else if(reg3.test(tagType)){
	    	for(var j=0;j<tag.options.length;j++){
	    		if(tag.options[j].selected){
	    		res.push(encodeURIComponent(tagVal)+"="+encodeURIComponent(tag.options[j].value||tag.options[j].text));   
	    		}
	    	}
	    }else{}
	}	
	return res.join("&");
}

发表于 2017-08-10 22:34:48 回复(0)
function serialize(form) {
    var parts = [];
    for (var i = 0, i1 = form.elements.length; i < i1; i++) {
        var field = form.elements[i];
        switch (field.type) {
            case 'select-one':
            case 'select-multiple':
                if (field.type.length) {
                    for (var j = 0, j1 = field.options.length; j < j1; j++) {
                        var option = field.options[j];
                        if (option.selected) {
                            var optionValue = '';
                            if (option.hasAttribute('value') && option.attributes['value'].specified) {
                                //specified表明是否有此属性,有的话返回true,若定义了此属性但尚未添加到元素中也返回true。
                                optionValue = option.value;
                            } else {
                                optionValue = optionValue.text;
                            }
                            parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(optionValue));
                        }
                    }
                }
                break;
            case undefined:
            case 'file':
            case 'submit':
            case 'reset':
            case 'button':
                break;
            case 'radio':
            case 'checkbox':
                if(!field.checked){
                    break;
                }else{
                    parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.dataset['index']));
                     break;
                }
            default:
                if(field.name.length){
                    parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
                }
        }

    }
    return parts.join('&');
}
发表于 2017-08-10 21:26:44 回复(0)
function date(form_id){ var name=form_id.name.value var passport =form_id.passport.value ..... json=['name':'xxx',passport':'xxx',...] Ajax.post{'url',json} }
发表于 2017-11-21 12:28:02 回复(0)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>form的序列化</title>
</head>
<body>
<form id="target">
    <select name="age">
        <option value="aaa">aaa</option>
        <option value="bbb">bbb</option>
        <option value="ccc">ccc</option>
        <option value="ddd" selected>ddd</option>
    </select>

    <input name="name" value="qiudeqing">
    <input type="password" name="password" value="11111">
    <input type="hidden" name="salery" value="3333">
    <textarea name="description">description</textarea>
    <input type="checkbox" name="hobby" value="football" checked>Football
    <input type="checkbox" name="hobby" value="basketball">Basketball
    <input type="radio" name="sex" value="Female" checked>Female
    <input type="radio" name="sex" value="Male">Male
</form>
<script>
//表单序列化通用函数
function serialize(form){
    var parts = [],field = null,i, j, len, optLen, option, optValue;
    for(i=0, len=form.elements.length; i<len; i++){
        field = form.elements[i];
        switch(field.type){
            case "select-one":       //单选框
            case "select-multiple":  //多选框
            if(field.name.length){
                for(j=0, optLen = field.options.length; j<optLen; j++){
                    option = field.options[j];
                    if(option.selected){
                        optValue = '';
                        if(option.hasAttribute){
                            optValue = (option.hasAttribute('value') ? option.value : option.text);  //非IE
                        }else{
                            optValue = (option.attributes['value'].specified ? option.value : option.text); //IE
                        }
                        parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(optValue));
                    }
                }
            }
            break;
 
            case undefined:  //字段集
            case "file":     //文件输入
            case "submit":   //提交按钮
            case "reset":    //重置按钮
            case "button":   //自定义按钮
            break;
 
            case "radio":    //单选按钮
            case "checkbox":  //复选按钮
                if(!field.checked){
                    break;
                }
 
            default:
            //不包含没有名字的表单字段
            if(field.name.length){
                parts.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value));
            }
        }
    }
    return parts.join(" & "); //查寻字符串格式输出
}
//页面加载完成调用表单序列化函数(一般是提交按钮,这里只看效果)
window.onload = function(){
    var form = document.getElementById('target');
    console.log(serialize(form));
};

</script>
</body>
</html>

发表于 2017-09-09 08:47:40 回复(0)
var form = document.getElementsByTagName('form')[0]
var result = {}

for(var i = 0, max = form.elements.length; i <max; i++){
	var elem = form.elements[i] 
	switch(elem.type){
		case undefined:
		case 'button':
		case 'file':
		case 'reset':
		case 'submit':
			break;

		case 'checkbox':
		case 'radio':
			if(!elem.checked){
				break;
			}

		default:
			if(result[elem.name]){
				result[elem.name] = result[elem.name] + ',' + elem.value
			}else{
				result[elem.name] = elem.value
			}
	}

	return result
}

发表于 2017-08-21 20:59:40 回复(0)
var form = document.forms[0];
serilizaForm(form); function serilizaForm(form){ var setForm = ""; for(var key in form){ if(form.hasOwnProperty(key)){ setForm += '"'+form[key].name+'"'+':'+'"'+form[key].value + '"'+',';
        }
    } setForm = "{" + setForm.slice(0,setForm.length -1) + "}"; console.log(setForm) console.log(JSON.parse(setForm)) return JSON.parse(setForm);
}
发表于 2017-08-10 20:40:32 回复(0)
function parameterize (form) {
	var inputs = [];
	var visit = function (node) {
		if(node.name){
			inputs.push(node);
		}
		for(var i = 0; i < node.children.length; i++){
			visit(node.children[i]);
		}
	}
	visit(form);
	var paramStr = "";
	for(var i = 0; i < inputs.length; i++){
		if(/radio|checkbox/.test(inputs[i].type)){
			if(inputs[i].checked){
				paramStr = paramStr + inputs[i].name + "=" + inputs[i].value + "&";
			}else{
				continue;
			}
		}else {
			paramStr = paramStr + inputs[i].name + "=" + inputs[i].value + "&";
		}
	}
	return paramStr.substring(0, paramStr.length - 1);
}

发表于 2017-08-10 16:49:52 回复(0)
							
function serializeForm() {
var form = document.forms[0];
var serForm = "";
for (var key in form) {
if (form.hasOwnProperty(key)) {
serForm += '"' + form[key].name + '"' + ":" + '"' + form[key].value + '"' + ",";
}
}
serForm = "{" + serForm.slice(0, serForm.length - 1) + "}";
return JSON.parse(serForm);
}
发表于 2017-08-10 11:10:29 回复(0)