将包含&,=的序列化字符串转换为Object?

时间:2017-02-02 11:52:41

标签: javascript jquery html

$('#submit-form').click(function(){
    var data_serialize = $("#form").serialize();
    $("input[type='checkbox']:not(:checked)").each(function(e){ 
          data_serialize += "&"+this.name+'=0';
    });
    $("input[type='checkbox']:checked").each(function(e){ 
          data_serialize += "&"+this.name+'=1';
    });
    console.log(data_serialize);
})

上面的代码给了我一个字符串

companyName=&contactName=&role=&email=&phone=&desctiption=&websiteURL=&tc-check=0
像这样。现在我想把它作为一个对象。请帮帮我

2 个答案:

答案 0 :(得分:2)

它会将此字符串转换为javascript对象。



var yourString = 'companyName=&contactName=&role=&email=&phone=&desctiption=&websiteURL=&tc-check=0';


var yourObj = JSON.parse('{"' + yourString.replace(/=/g,'":"').replace(/&/g, '","') + '"}');


console.log(JSON.stringify(yourObj));




答案 1 :(得分:1)

您可以通过括号表示法轻松遍历构建对象的表单控件:

$('#submit-form').click(function(){
    var obj = {};
    $("#form").find("input, textarea, select").each(function() {
        var type = this.type.toLowerCase();
        if (this.name && !this.disabled && type !== "button" && type !== "submit") {
            if (type === "checkbox") {
                obj[this.name] = this.checked ? 1 : 0;
            } else {
                obj[this.name] = $(this).val();
            }
        }
    });
    console.log(obj);
});

请注意,我们跳过没有名称的禁用输入和输入,因为它是表单的标准(它是HTML的作用,以及serialize的作用)。以上内容保留了您对复选框的非标准处理。

示例:



$('#submit-form').click(function(){
    var obj = {};
    $("#form").find("input, textarea, select").each(function() {
        var type = this.type.toLowerCase();
        if (this.name && !this.disabled && type !== "button" && type !== "submit") {
            if (type === "checkbox") {
                obj[this.name] = this.checked ? 1 : 0;
            } else {
                obj[this.name] = $(this).val();
            }
        }
    });
    console.log(obj);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <input name="btn" type="button" value="Buttons are ignored">
  <input name="text1" type="text" value="text here">
  <input name="cb1" type="checkbox" checked>
  <input name="cb2" type="checkbox">
  <select name="s1">
    <option value="foo" selected>foo</option>
    <option value="bar">bar</option>
  </select>
  <textarea name="ta">testing</textarea>
  <input name="text-disabled" type="text" disabled value="don't include me">
  <input type="text" value="Ignore me I don't have a name">
  <input type="button" id="submit-form" value="Submit">
</form>
&#13;
&#13;
&#13;