使用 jQuery 将表单数据转换为 JavaScript 对象

How do I convert all elements of my form to a JavaScript object?

I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by $('#formid').serialize();, nor do I want the map returned by $('#formid').serializeArray();

转载于:https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery

csdnceshi80
胖鸭 check this stackoverflow.com/a/39248551/6293856
2 年多之前 回复
csdnceshi54
hurriedly% It's possible, but it will fail for forms that have multiple inputs with the same name value (e.g. name="foo[]"). Both .serialize() and .serializeArray() handle that case. I'm assuming your specific use case doesn't use that pattern.
接近 4 年之前 回复
csdnceshi57
perhaps? the link in your comment is now a 404.
大约 5 年之前 回复
csdnceshi59
ℙℕℤℝ A good js I came across >> github.com/marioizquierdo/jquery.serializeJSON
7 年多之前 回复
csdnceshi75
衫裤跑路 - There are other reasons besides submission/transmission for using a form element. If you're doing any heavy lifting with the form values within JavaScript (e.g. single page app), it's very handy to have them in an object format for accessing & manipulating. Also, HTTP Post and Get query strings aren't the only formats for moving data around.
8 年多之前 回复
csdnceshi52
妄徒之命 All of the below methods are insane, just use $.serialize, it is transmitted just as well in a POST as in a GET.
8 年多之前 回复
csdnceshi62
csdnceshi62 VOTE 100! Enjoy your badge :)
接近 9 年之前 回复
weixin_41568127
?yb? Yes, I'd say the correct answer uses Crockford's lib and Tobias' function like so: JSON.stringify($('myForm').serializeObject())
接近 10 年之前 回复
csdnceshi76
斗士狗 - The accepted answer using D. Crockford's JSON-js library. Here's an example: github.com/tleese22/google-app-engine-jappstart/blob/master/src/…
接近 10 年之前 回复
weixin_41568127
?yb? I don't see any answer on there that addresses the specific question better than Tobias' answer below.
接近 10 年之前 回复
csdnceshi76
斗士狗 This question has a better solution: stackoverflow.com/questions/191881/…
10 年多之前 回复
csdnceshi60
℡Wang Yan If you are trying to convert all form fields to JSON in order to submit this form through Ajax here is a jQuery form plugin that does that.
11 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 because the first returns a string, exactly like what you'd get if you submitted the form with a GET method, and the second gives you a array of objects, each with a name value pair. I want that if i have a field named "email" i get an object that will allow me to retrieve that value with obj.email. With serializeArray(), i'd have to do something like obj[indexOfElement].value
11 年多之前 回复
csdnceshi69
YaoRaoLov I'm not understanding why either of those methods are sufficient for your needs?
11 年多之前 回复

30个回答

serializeArray already does exactly that. You just need to massage the data into your required format:

function objectifyForm(formArray) {//serialize data function

  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }
  return returnArray;
}

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.

csdnceshi79
python小菜 const data = $(form).serializeArray().reduce((acc, next) => ({ ...acc, [next.name]: next.value }), {})
2 年多之前 回复
csdnceshi75
衫裤跑路 Modern version of the above: form.serializeArray().reduce(function(acc,cur) { acc[cur.name] = cur.value return acc }, {})
大约 3 年之前 回复
weixin_41568134
MAO-EYE Does anyone know if this is still maintained? Should I avoid using it???
3 年多之前 回复
csdnceshi70
笑故挽风 Thanks a lot, it's just what I was looking for.
3 年多之前 回复
weixin_41568174
from.. From css-tricks.com/snippets/jquery/serialize-form-to-json Excellent snippet
接近 4 年之前 回复
csdnceshi68
local-host better than the alternative than to massage an array into a JSON object using string manipulations
4 年多之前 回复
csdnceshi67
bug^君 you just saved my valuable time, thank you :)
接近 5 年之前 回复
csdnceshi58
Didn"t forge You simply rock!
接近 5 年之前 回复
csdnceshi55
~Onlooker If you use jquery to post this object to the server, and you have a multiple select on your form, and the name of your control is 'foo', then jquery will send 'foo' if only one item is selected and 'foo[]' if multiple items are selected. This will be very confusing on the server side.
大约 5 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 - I think Ben Alman provides a better solution: benalman.com/projects/jquery-misc-plugins/#serializeobject. You also use o[this.name] in multiple places, and that should be cached for faster performance: var oname = o[this.name];
5 年多之前 回复
weixin_41568110
七度&光 and for files the type="file". Is it possible?
5 年多之前 回复
csdnceshi69
YaoRaoLov I know this is quite an old thread, but I updated you function to serialize disabled fields as well. Hope it helps!
接近 6 年之前 回复
csdnceshi77
狐狸.fox I use this function all the time and it works fantastic. Just wanted to counterpoint all the negative feedback. No bulky plugins, works fast and reliably. Support VALID html so that's all I needed.
6 年多之前 回复
csdnceshi61
derek5. Shouldn't this code be added to jQuery? It really needs to be implemented.
6 年多之前 回复
csdnceshi60
℡Wang Yan Would like to suggest this improvement: jsfiddle.net/S9MY8/1 The difference is it handles keys in the input name, e.g. name="test[1]" and preserves these in an object. so rather than: "test[]" : ['val1','val2'] you would have: "test" : { 1 : 'val1', 2 : 'val2' } This worked better for my purposes anyway, passing form values into an underscore template.
6 年多之前 回复
csdnceshi65
larry*wei change:case 'checkbox': if (val === 'on' || val === 'checked' || val === true || val === 1) $el.attr('checked', 'checked'); else $el.attr('checked', null);
6 年多之前 回复
csdnceshi54
hurriedly% The jQuery plugin serializeJSON uses serailizeArray under the hood to serialize complex forms into the same format as Rails params: github.com/marioizquierdo/jquery.serializeJSON
接近 7 年之前 回复
csdnceshi76
斗士狗 treats a select with only one option selected as a string. where there is potential for mulitple options and only one is selected, it should be treated as an array. i'm working on something to remedy this.
7 年多之前 回复
csdnceshi74
7*4 jQuery itself should provide this function in most recent next version, don't you think so?
7 年多之前 回复
csdnceshi71
Memor.の Meacham, I believe you should be using the readonly attribute, not disabled, if you want to include the inputs on the form submission/serialization.
7 年多之前 回复
weixin_41568183
零零乙 This is great but it doesn't parse data types. It makes all the values strings. Maybe that should be handled elsewhere but it's a caveat to this snippet. Still, amazingly useful for how simple it is. Thanks!
接近 8 年之前 回复
weixin_41568127
?yb? I know this is a few months old, but since when did do arrays use non-numeric indexes? No one should name an input foo[bar] and hope to treat it as an array. Are you confusing arrays and hashes? Yes, [] is commonly understood to be an accessor but not just for arrays. Also saying it's valid HTML but not in the HTML spec is a contradiction. Yes, the browser may not choke on it, but not many webservers are going to know how to deserialize that like they would an array. Why? Because its not in the HTML spec. Therefore, it is indeed invalid.
大约 8 年之前 回复
weixin_41568131
10.24 I never said the HTML spec says they should be treated specially. I was simply arguing that foo[bar]-type names are completely valid and [] is commonly understood to be an array accessor; why not handle them as such? Or to pose it a bit differently, in what scenario would you name an input foo[bar] and not wish to treat foo as an array?
8 年多之前 回复
csdnceshi56
lrony* Could you show me where in the HTML spec it says that inputs named in this format should be treated specially?
8 年多之前 回复
weixin_41568131
10.24 I understand not wanting to support it, but saying it's "not a standard part of HTML forms" is neither correct or a valid counter point. An input named foo[bar] is certainly valid; atop that, adding support for the intended functionality results in a more robust and flexible solution.
8 年多之前 回复
csdnceshi63
elliott.david The foo[bar] type input is a PHP only parsing thing, but I too find it very useful. Using Tobias's great solution above, I modified it to correctly handle the foo[bar] case. I just whipped this up in about 5 minutes so I'm sure it can be made a lot neater. Okay, it seems I can't post it in a comment, so see my answer below
8 年多之前 回复
csdnceshi56
lrony* I think you might be looking for an answer to a different question. foo[bar] style input naming is common convention in a number of web frameworks, but it's certainly not a standard part of HTML forms, it's not mentioned in the question, and I've made no attempt to deal with it here.
接近 9 年之前 回复
weixin_41568131
10.24 It doesn't handle foo[bar]-type inputs as expected, not to mention most of the other input name varieties. After being very frustrated with shallow solutions to this problem, I ended up writing my own jQuery plugin -- details in the answer I provided to this question.
接近 9 年之前 回复
csdnceshi56
lrony* Is there something specific about it that you've found problematic? I wrote this code in about 5 minutes to answer the question as asked, and it seems to have worked fine for the OP, as well as for many others.
接近 9 年之前 回复
weixin_41568131
10.24 This is so rigid, it's mind-blowing that it ever received more than a couple upvotes.
接近 9 年之前 回复
csdnceshi62
csdnceshi62 This doesn't work for general case. It produce invalid results for name="model[property_name]". It also doesn't handle nested properties. name="model[prop_1][prop_2]". So it should not considered as answer.
大约 9 年之前 回复
csdnceshi72
谁还没个明天 Plugin by Ben Alman can also be used: benalman.com/projects/jquery-misc-plugins/#serializeobject
大约 9 年之前 回复
weixin_41568184
叼花硬汉 This solution contains a bug where "falsy" values such as 0, '', and false won't be serialized correctly. I have posted a fixed solution.
9 年多之前 回复
csdnceshi78
程序go The $.toJson in your referenced example does not exist (any more). Also even in your sample the inner expression does not catch all form elements (e.g. checkboxes status, ...).
9 年多之前 回复
csdnceshi80
胖鸭 Samuel Meacham, you may want to use readonly elements instead of disabled ones.
9 年多之前 回复
weixin_41568126
乱世@小熊 serializeObject() is half the solution - the other half is the Crockford JSON lib. Full solution is therefore: JSON.stringify($('myForm').serializeObject())
接近 10 年之前 回复
csdnceshi51
旧行李 I think you need to add this to your code just after each statement:<pre>this.name=this.name.replace('[]','');</pre> if not, then there would be error in parsing JSON.
大约 10 年之前 回复
csdnceshi59
ℙℕℤℝ Be warned, serializeArray() will not include disabled elements. I often disable input elements that are sync'd to other elements on the page, but I still want them included in my serialized object. You're better off using something like $.map( $("#container :input"), function(n, i) { /* n.name and $(n).val() */ } ); if you need to include disabled elements.
10 年多之前 回复
csdnceshi57
perhaps? Thanks Tobias, was looking for a best practice.
大约 11 年之前 回复
csdnceshi56
lrony* Do you mean "why use serializeArray to get the data in the first place?" Because serializeArray is already written, is unit tested in multiple browsers, and could theoretically be improved in later versions of jQuery. The less code you write that has to access inconsistent things like DOM elements directly, the more stable your code will be.
11 年多之前 回复
weixin_41568208
北城已荒凉 as tvanfosson says, why iterate over the collection twice?
11 年多之前 回复

What's wrong with:

var data = {};
$(".form-selector").serializeArray().map(function(x){data[x.name] = x.value;}); 
csdnceshi61
derek5. Works perfectly supported in all the browser as well
大约 3 年之前 回复
csdnceshi79
python小菜 this doesn't support foo[xxx] = 1, foo[yyy] = 2 you should get: foo: { xxx:1, yyy:2} but in this case you get {foo[xxx]:1, foo[yyy]:2}
大约 3 年之前 回复
csdnceshi76
斗士狗 when u have multiple checkbox that belong to same field, when u leave all unchecked, u should get empty array
3 年多之前 回复
csdnceshi74
7*4 This really is the simplest way to flatten the array to a key->value hash. Of course, there's no need for map since you're not over-writing the original array, just use forEach. Like this: var data = {}; $(".form-selector").serializeArray().forEach(function(x){data[x.name] = x.value;}); Simple, complete, and effective.
3 年多之前 回复
csdnceshi53
Lotus@ Awesome! Super simple!
接近 4 年之前 回复
weixin_41568174
from.. and what about $($("form").find(":input").serializeArray()).each(function(k,v) { form[v.name] = v.value})
4 年多之前 回复
weixin_41568131
10.24 I would disagree regarding "type detection" not necessary at all, .serializeArray() should handle the types like checkbox multiple (for select) etc... values are already what they are, this is simple case of flattening the object.
大约 5 年之前 回复
csdnceshi72
谁还没个明天 In the case of a multiple select input, this only returns the last value.
大约 5 年之前 回复
csdnceshi62
csdnceshi62 $(this).serializeArray().reduce(function(m,o){ m[o.name] = o.value; return m;}, {})
5 年多之前 回复
weixin_41568127
?yb? If you want a pure jQuery solution, you could use var form = {}; $.each($(this).serializeArray(), function (i, field) { form[field.name] = field.value || ""; });
5 年多之前 回复
csdnceshi68
local-host It's so simple because it's super naive... doesn't handle checkboxes with same name. Each time it will override checked item before it. You'll definitely need some input type detection to ensure it's properly serialized.
5 年多之前 回复
csdnceshi65
larry*wei Every time basic way is the best. Thanks @user1953157
接近 6 年之前 回复
csdnceshi58
Didn"t forge Love this answer- thanks!
接近 6 年之前 回复
csdnceshi75
衫裤跑路 if you're not returning anything, why don't you just use .each instead of .map ??
接近 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 - if nothing is selected, why would you want it on your back end? if you must select an option, validate the input before serializing.
大约 6 年之前 回复
csdnceshi67
bug^君 Very simple and effective, but how do you make it account for radio groups where no radio is selected?
接近 7 年之前 回复

Convert forms to JSON LIKE A BOSS


Current source is on GitHub and bower.

$ bower install jquery-serialize-object


The following code is now deprecated.

The following code can take work with all sorts of input names; and handle them just as you'd expect.

For example:

<!-- all of these will work! -->
<input name="honey[badger]" value="a">
<input name="wombat[]" value="b">
<input name="hello[panda][]" value="c">
<input name="animals[0][name]" value="d">
<input name="animals[0][breed]" value="e">
<input name="crazy[1][][wonky]" value="f">
<input name="dream[as][vividly][as][you][can]" value="g">
// output
{
  "honey":{
    "badger":"a"
  },
  "wombat":["b"],
  "hello":{
    "panda":["c"]
  },
  "animals":[
    {
      "name":"d",
      "breed":"e"
    }
  ],
  "crazy":[
    null,
    [
      {"wonky":"f"}
    ]
  ],
  "dream":{
    "as":{
      "vividly":{
        "as":{
          "you":{
            "can":"g"
          }
        }
      }
    }
  }
}

Usage

$('#my-form').serializeObject();

The Sorcery (JavaScript)

(function($){
    $.fn.serializeObject = function(){

        var self = this,
            json = {},
            push_counters = {},
            patterns = {
                "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
                "push":     /^$/,
                "fixed":    /^\d+$/,
                "named":    /^[a-zA-Z0-9_]+$/
            };


        this.build = function(base, key, value){
            base[key] = value;
            return base;
        };

        this.push_counter = function(key){
            if(push_counters[key] === undefined){
                push_counters[key] = 0;
            }
            return push_counters[key]++;
        };

        $.each($(this).serializeArray(), function(){

            // skip invalid keys
            if(!patterns.validate.test(this.name)){
                return;
            }

            var k,
                keys = this.name.match(patterns.key),
                merge = this.value,
                reverse_key = this.name;

            while((k = keys.pop()) !== undefined){

                // adjust reverse_key
                reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                // push
                if(k.match(patterns.push)){
                    merge = self.build([], self.push_counter(reverse_key), merge);
                }

                // fixed
                else if(k.match(patterns.fixed)){
                    merge = self.build([], k, merge);
                }

                // named
                else if(k.match(patterns.named)){
                    merge = self.build({}, k, merge);
                }
            }

            json = $.extend(true, json, merge);
        });

        return json;
    };
})(jQuery);
csdnceshi58
Didn"t forge Please explain what "The following code is now deprecated." means. In favor of what?
接近 2 年之前 回复
csdnceshi68
local-host as you said ... it worked like a boss
2 年多之前 回复
weixin_41568134
MAO-EYE thanks man, you are my hero
2 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 I have this input: <input name="vehicle[]" value="0"> <input name="vehicle[]" value="1"> <input name="vehicle[]" value="2"> <input name="vehicle[]" value="3"> <input name="vehicle[3]" value="4"> <input name="vehicle[2]" value="5"> <input name="vehicle[]" value="6"> <input name="vehicle[rt]" value="7"> Natively, in PHP I see: "vehicle" => array:6 [▼ 0 => "0" 1 => "1" 2 => "5" 3 => "4" 4 => "6" "rt" => "7" ] Use AJAX and your method, in PHP I see: "vehicle" => array:1 [ "rt" => "7" ] Behavior is not same, specific to PHP?
大约 4 年之前 回复
csdnceshi79
python小菜 it doesn't return an object literal. That's misunderstanding the concept of a literal. It just returns an object.
大约 4 年之前 回复
csdnceshi56
lrony* thank you so much. best solution what i have ever seen for multidimensional forms!
接近 5 年之前 回复
csdnceshi78
程序go all support for this project has moved to Github. Please read the readme.
大约 5 年之前 回复
weixin_41568131
10.24 How can I use brackets for arrays and dots for properties? Example of form names: <input name='people[0].first' value='Bill', people[0].last='Henderson' /> <input name='people[1].first' value='Jane', people[1].last='Henderson' /> needs to become: {people:[{'first':'Bill','last':'Henderson'},{'first':'Jane','last':'Henderson'}]}...This is the way the default model binder in mvc works (and the output is nice and transparent too).
大约 5 年之前 回复
csdnceshi73
喵-见缝插针 thanks for that!
5 年多之前 回复
csdnceshi59
ℙℕℤℝ +1 This is clearly the best answer.
6 年多之前 回复
csdnceshi78
程序go If you're referring to the [null,null,...,null,1], this is not a leak. Please see this issue. Also, please update the version of the plugin you're using. I can only afford to support the current version.
6 年多之前 回复
csdnceshi57
perhaps? I ran into another issue with the function today. I think that i may have found a leak. Author, could you please explain why: jsfiddle.net/VX9RW/1 happens?
6 年多之前 回复
csdnceshi57
perhaps? Today i had a problem with multiple-select fields. If they were empty (=no selection) no value would get sent to the server (this is correct behaviour!), thus the server would not recognize that the selection was (more or less) reset to nothing. So if anyone runs into this problem: i solved it by adding a hidden form field before each multiple-select, with the same name. Therefore if no value is selected in the multiple-select, an empty value with the same form field name is sent to the server and there you can deal with the thing accordingly.
6 年多之前 回复
csdnceshi69
YaoRaoLov I agree that this is the more robust solution. If you have more than just a flat set of data you will need this solution. In my case, I have arrays of sub types (e.g. Reservations have an array of Payments). This solutions returned an array of subdocuments called Payments with each payment attribute. Love it!
6 年多之前 回复
csdnceshi57
perhaps? This solution should be on top as it deals with the problem of nested keys as form element names.
6 年多之前 回复
csdnceshi67
bug^君 Wanted to point out that github.com/serbanghita/formToObject is a similar JavaScript method (no 3rd party libraries needed) that does the same job. Supports 'multiple', ignores 'disabled' elements.
大约 7 年之前 回复
csdnceshi78
程序go I didn't realize he left a comment on this answer too. Anyone following @rix's (invalid) bug, please see the github issue
大约 7 年之前 回复
csdnceshi77
狐狸.fox it does not work because jsfiddle refuses to load jquery plugin due to "its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled" I have copied the JS source of jquery plugin which is above in this answer. here is updated demo: jsfiddle.net/ihusnjak/QqT2w/2
大约 7 年之前 回复
weixin_41568196
撒拉嘿哟木头 Hi, I made a fiddle using select boxes and can't get this to work - jsfiddle.net/QqT2w/1
大约 7 年之前 回复
csdnceshi78
程序go I did a test for here on jsfiddle. The trick is to name your select properly. <select name="foo" multiple="multiple"> will not work in any scenario. However, if you use [], as in <select name="bar[]" multiple="multiple">, it will work just fine :)
7 年多之前 回复
csdnceshi72
谁还没个明天 Unfortunately it doesn't work well for <select> with multiple - returns only first selected option value as string instead of array with all selected options.
7 年多之前 回复
csdnceshi78
程序go I never understood your comment. This is using jQuery's .serializeArray() so it's just constructing a new object with key/value pairs; nothing else.
接近 8 年之前 回复
csdnceshi54
hurriedly% works like a charm! thanks!
接近 8 年之前 回复
csdnceshi75
衫裤跑路 actually, toJSON is exactly what the spec says it should be called: developer.mozilla.org/en/JSON#toJSON()_method an unfortunate misnomer.
8 年多之前 回复
weixin_41568127
?yb? re: hasOwnProperty, check out the docs on MDN
8 年多之前 回复
csdnceshi61
derek5. It would be very cool if you be a little more explicit or even do a pull request on Github for this (I'm not sure what you mean with the hasOwnProperty remark)
8 年多之前 回复
weixin_41568127
?yb? So, that works pretty well. But it's misnamed: it doesn't return JSON, as the name implies. Instead, it returns an object literal. Also, it's important to check for hasOwnProperty, otherwise your arrays have anything that's attached to their prototype, like: {numbers: ["1", "3", indexOf: function(){...}]}
接近 9 年之前 回复

This function should handle multidimensional arrays along with multiple elements with the same name.

I've been using it for a couple years so far:

jQuery.fn.serializeJSON=function() {
  var json = {};
  jQuery.map(jQuery(this).serializeArray(), function(n, i) {
    var _ = n.name.indexOf('[');
    if (_ > -1) {
      var o = json;
      _name = n.name.replace(/\]/gi, '').split('[');
      for (var i=0, len=_name.length; i<len; i++) {
        if (i == len-1) {
          if (o[_name[i]]) {
            if (typeof o[_name[i]] == 'string') {
              o[_name[i]] = [o[_name[i]]];
            }
            o[_name[i]].push(n.value);
          }
          else o[_name[i]] = n.value || '';
        }
        else o = o[_name[i]] = o[_name[i]] || {};
      }
    }
    else {
      if (json[n.name] !== undefined) {
        if (!json[n.name].push) {
          json[n.name] = [json[n.name]];
        }
        json[n.name].push(n.value || '');
      }
      else json[n.name] = n.value || '';      
    }
  });
  return json;
};

Another answer

document.addEventListener("DOMContentLoaded", function() {
  setInterval(function() {
    var form = document.getElementById('form') || document.querySelector('form[name="userprofile"]');
    var json = Array.from(new FormData(form)).map(function(e,i) {this[e[0]]=e[1]; return this;}.bind({}))[0];
    
    console.log(json)
    document.querySelector('#asJSON').value = JSON.stringify(json);
  }, 1000);
})
<form name="userprofile" id="form">
  <p>Name <input type="text" name="firstname" value="John"/></p>
  <p>Family name <input name="lastname" value="Smith"/></p>
  <p>Work <input name="employment[name]" value="inc, Inc."/></p>
  <p>Works since <input name="employment[since]" value="2017" /></p>
  <p>Photo <input type="file" /></p>
  <p>Send <input type="submit" /></p>
</form>

JSON: <textarea id="asJSON"></textarea>

FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData

</div>

Use:

function form_to_json (selector) {
  var ary = $(selector).serializeArray();
  var obj = {};
  for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
  return obj;
}

Output:

{"myfield": "myfield value", "passwordfield": "mypasswordvalue"}
csdnceshi55
~Onlooker nice. simple ,short and straight to the point
4 年多之前 回复

One-liner (no dependencies other than jQuery), uses fixed object binding for function passsed to map method.

$('form').serializeArray().map(function(x){this[x.name] = x.value; return this;}.bind({}))[0]

What it does?

"id=2&value=1&comment=ok" => Object { id: "2", value: "1", comment: "ok" }

suitable for progressive web apps (one can easily support both regular form submit action as well as ajax requests)

Using maček's solution, I modified it to work with the way ASP.NET MVC handles their nested/complex objects on the same form. All you have to do is modify the validate piece to this:

"validate": /^[a-zA-Z][a-zA-Z0-9_]*((?:\[(?:\d*|[a-zA-Z0-9_]+)\])*(?:\.)[a-zA-Z][a-zA-Z0-9_]*)*$/,

This will match and then correctly map elements with names like:

<input type="text" name="zooName" />

And

<input type="text" name="zooAnimals[0].name" />

I coded a form to a multidimensional JavaScript object myself to use it in production. The result is https://github.com/serbanghita/formToObject.js.

csdnceshi68
local-host Thanks for letting me know that it's useful. I have some incoming features to roll and this motivates me.
接近 7 年之前 回复
csdnceshi61
derek5. I used a variation of this for a very specific implementation, thanks a lot!
接近 7 年之前 回复

Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.

var values = $(this).serialize(),
attributes = {};

values.replace(/([^&]+)=([^&]*)/g, function (match, name, value) {
    attributes[name] = value;
});
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐