Serialize form data to JSON

This question already has an answer here:

  • Convert form data to JavaScript object with jQuery 50 answers

  • Here's a function for this use case:

    function getFormData($form){
        var unindexed_array = $form.serializeArray();
        var indexed_array = {};
    
        $.map(unindexed_array, function(n, i){
            indexed_array[n['name']] = n['value'];
        });
    
        return indexed_array;
    }
    

    Usage:

    var $form = $("#form_data");
    var data = getFormData($form);
    

    你可以这样做:

    function onSubmit( form ){
      var data = JSON.stringify( $(form).serializeArray() ); //  <-----------
    
      console.log( data );
      return false; //don't submit
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form onsubmit='return onSubmit(this)'>
      <input name='user' placeholder='user'><br>
      <input name='password' type='password' placeholder='password'><br>
      <button type='submit'>Try</button>
    </form>

    The below code should help you out. :)

     //The function is based on http://css-tricks.com/snippets/jquery/serialize-form-to-json/
     <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
    
    <script>
        $.fn.serializeObject = function() {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    
        $(function() {
            $('form.login').on('submit', function(e) {
              e.preventDefault();
    
              var formData = $(this).serializeObject();
              console.log(formData);
              $('.datahere').html(formData);
            });
        });
    </script>
    
    链接地址: http://www.djcxy.com/p/46326.html

    上一篇: 如何获取表单数据作为jQuery中的对象

    下一篇: 将表单数据序列化为JSON