簡體   English   中英

將包含&,=的序列化字符串轉換為Object?

[英]Convert serialized string that contains &, = to Object?

$('#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

像這樣。 現在,我想使其成為一個對象。 請幫我

它將將此字符串轉換為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)); 

您可以輕松地通過括號表示法遍歷表單控件來構建對象:

$('#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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM