求大神写个类似于JQ的serialize的方法

我传一个URL和一个form表单元素。生成一个带参数的URL。。。。。。

阅读 1.6k
1 个回答

仿照着jq写了一个,用法一样的。

function serialize(a, traditional) {
  var prefix, s = [];

  if ('[object HTMLFormElement]' === Object.prototype.toString.call(a)) a = a.childNodes;

  if (["[object Array]", "[object NodeList]"].indexOf(Object.prototype.toString.call(a)) >= 0) {
    Array.prototype.forEach.call(a, function(v) {
      if (!v.name || v.disabled) return;
      if ((v.type === 'radio' || v.type === 'checkbox') && !v.checked) return;
      add(v.name, v.value);
    });
  } else {
    for (prefix in a) buildParams(prefix, a[prefix], traditional, add);
  }

  return s.join("&");

  function add(key, valueOrFunction) {
    var value = typeof valueOrFunction === 'function' ? valueOrFunction() : valueOrFunction;
    s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
  }

  function buildParams(t, e, n) {
    var r;
    if ("[object Array]" === Object.prototype.toString.call(e)) {
      Array.prototype.map.call(e, function(e, r) {
        o(t + "[" + ("object" == typeof e && null !== e ? r : "") + "]", e, n)
      });
    } else if ("[object Object]" === Object.prototype.toString.call(e)) {
      for (r in e) buildParams(t + "[" + r + "]", e[r], n);
    } else {
      n(t, e);
    }
  }
}

测试,点开看效果:
https://jsfiddle.net/ztv676p1/

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题