jQuery 表单序列化 serialize() 时过滤部分 input 元素方法

  举个栗子,我们 $('form').serialize() 某个表单时,不想提交某个 input,或者我们需要对某个 input 修改,此时就需要用到过滤。

两种场景

一、不想提交某个 input

  这个非常简单,只需要把那个 input 里面的 name 属性删掉就行

二、过滤/重组某个 input

  假设我们需要提交 type="password" 密码,直接 submit 或者 post 过去是明文的,我们想 md5sha1 一下,两种方法:

  1. 在序列化之前,将原 input 的值加密一次再返回去,然后再 serialize(),缺点很明显,如果第一次提交失败了,第二次肯定就是提示你两次密码不同了。

  2. 在序列化时,用 jQuery 过滤掉密码,然后重新组装一下:

    // 用 data 存储序列化后的字符串
    var data = $('form').find(":not('input[type='password']')").serialize();
    // 此时得到的 data 是没有密码的
    // 最后重新组装一下。此时提交过去的 password 就是一个 md5 后的值了
    data += '&password=' + md5($('#password').val());

    md5 插件在这儿:https://github.com/blueimp/JavaScript-MD5


网上的序列化过滤 not 写法似乎有点问题…

猜你喜欢

转载自blog.csdn.net/maxsky/article/details/79222942