Created
          May 1, 2020 10:39 
        
      - 
      
- 
        Save xuhen/8eed91a4681dbaad31031fc4676b76a1 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // 将form序列化为key1=value1&key2=value2这样的个数,在ajax提交form表单时很有用。 | |
| function serialize(form) { | |
| var parts = [], | |
| field = null, i, | |
| len, | |
| j, 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); | |
| } else { | |
| optValue = (option.attributes["value"].specified ? | |
| option.value : option.text); | |
| } | |
| 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("&"); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment