Object.prototype.serialize = function () {var res = [], //存放结果的数组current = null, //当前循环内的表单控件i, //表单NodeList的索引len, //表单NodeList的长度k, //select遍历索引optionLen, //select遍历索引option, //select循环体内optionoptionValue, //select的valueform = 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("&");}--------------------------------------------------------------------------------//注册document.querySelector('#regBox form').onsubmit = function (e) {e.preventDefault()// 发送axios注册请求axios({url: '/api/reguser',method: 'post',data: this.serialize()}).then(({ data: res }) => {//成功回调console.log(res)})}//登录document.querySelector('#loginBox form').onsubmit = function (e) {e.preventDefault()axios({url: '/api/login',method: 'POST',data: this.serialize()}).then(({ data: res }) => {//成功回调console.log(res)});}
对HTML表单使用:
1.formElement.serialize();
2.复制代码
