温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS中如何使用serialize()

发布时间:2021-08-18 15:08:50 来源:亿速云 阅读:304 作者:小新 栏目:web开发

这篇文章主要介绍了JS中如何使用serialize(),具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

具体如下:

在实际开发场景中,难免遇到需要多个表单的数据传递问题。

之所以要进行多表单的数据传递是因为可以进行数据分组,便于数据的维护。

这个时候,出于不依赖jquery的考虑,有一个原生js函数来解决这个问题无疑是最好的。而源自于《JavaScript高级程序设计》一书的serialize()函数就是解决这个问题的最好办法,该函数如下:

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:   //fieldset
          case "file":    //file input
          case "submit":   //submit button
          case "reset":    //reset button
          case "button":   //custom button
            break;
          case "radio":    //radio button
          case "checkbox":  //checkbox
            if (!field.checked){
              break;
            }
            /* falls through */
          default:
            //don't include form fields without names
            if (field.name.length){
              parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
            }
        }
      }
      console.log(parts);
      return parts.join("&");
}

对于读过《JavaScript高级程序设计》的小伙伴来说,这个函数肯定不陌生;

但是如果我们传递的是一个对象,那么这个函数显然就不符合要求,而在这个开发需求下,我们改下这个函数,改造后函数如下

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);
                  }
                  //将数据改为对象形式
                  Object.defineProperty(parts, encodeURIComponent(field.name), {
                    value:encodeURIComponent(optValue),
                    enumerable:true //为真表示可枚举,只有可枚举才能出现在JSON.stringify()转换的json数据中
                  });
                }
              }
            }
            break;
          case undefined:   //fieldset
          case "file":    //file input
          case "submit":   //submit button
          case "reset":    //reset button
          case "button":   //custom button
            break;
          case "radio":    //radio button
          case "checkbox":  //checkbox
            if (!field.checked){
              break;
            }
            /* falls through */
          default:
            //don't include form fields without names
            if (field.name.length){
              //构建对象
              Object.defineProperty(parts, encodeURIComponent(field.name), {
                    value:encodeURIComponent(field.value),
                    enumerable:true  //为真表示可枚举,只有可枚举才能出现在JSON.stringify()转换的json数据中
                  });
            }
        }
      }
      console.log(parts);
      return parts;
}

于是,表单数据改为对象显示。如果有多个表单将表单保存到一个数组之中,利用JSON.stringify()转为json格式,传给后端;

注意:

利用Object.defineProperty创建对象,要加上 enumerable:true,否则json格式中不会出现对应的对象数据。这个纯粹是JSON.stringify()的要求。

感谢你能够认真阅读完这篇文章,希望小编分享的“JS中如何使用serialize()”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI