将表单数据序列化为JSON

这个问题在这里已经有了答案:

  • 使用jQuery将表单数据转换为JavaScript对象50个答案

  • 以下是这个用例的一个函数:

    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;
    }
    

    用法:

    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 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/46325.html

    上一篇: Serialize form data to JSON

    下一篇: Serializing QGraphicsScene contents