jQuery 将表单数据序列化为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11338774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:29:36  来源:igfitidea点击:

Serialize form data to JSON

jquerybackbone.jsunderscore.js

提问by dev.pus

I want to do some pre-server-validation of a form in a Backbone.js model. To do this I need to get the user input from a form into usable data. I found three methods to do this:

我想对Backbone.js模型中的表单进行一些服务器前验证。为此,我需要将用户从表单中输入的内容转化为可用数据。我找到了三种方法来做到这一点:

  1. var input = $("#inputId").val();
  2. var input = $("form.login").serialize();
  3. var input = $("form.login").serializeArray();
  1. var input = $("#inputId").val();
  2. var input = $("form.login").serialize();
  3. var input = $("form.login").serializeArray();

Unfortunately, none of the provide a good reabable and developable JSON object which I require. I already looked through several questions on Stack Overflow, but I found only some extra libraries.

不幸的是,没有一个提供我需要的良好的可恢复和可开发的 JSON 对象。我已经查看了有关 Stack Overflow 的几个问题,但我只找到了一些额外的库。

Doesn't Underscore.js, the current jQuery or Backbone.js provide a helper method?

Underscore.js,目前的jQuery或Backbone.js的提供一个辅助方法?

I can't imagine there is no request for such a function.

我无法想象没有人要求这样的功能。

HTML

HTML

<form class="login">
    <label for="_user_name">username:</label>
    <input type="text" id="_user_name" name="user[name]" value="dev.pus" />
    <label for="_user_pass">password:</label>
    <input type="password" id="_user_pass" name="user[pass]" value="1234" />
    <button type="submit">login</button>
</form>

JavaScript

JavaScript

var formData = $("form.login").serializeObject();
console.log(formData);

Outputs

输出

{
    "name": "dev.pus",
    "pass": "1234"
}

Backbone.js model

Backbone.js 模型

var user = new User(formData);
user.save();

回答by Maciej Pyszyński

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

回答by Mohammad Adil

You can do this:

你可以这样做:

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>

see this: http://www.json.org/js.html

看到这个:http: //www.json.org/js.html

回答by STEEL

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>

回答by Maertz

Use:

用:

var config = {};
jQuery(form).serializeArray().map(function(item) {
    if ( config[item.name] ) {
        if ( typeof(config[item.name]) === "string" ) {
            config[item.name] = [config[item.name]];
        }
        config[item.name].push(item.value);
    } else {
        config[item.name] = item.value;
    }
});

回答by ryanday

I know this doesn't meet the helper function requirement, but the way I've done this is using jQuery's $.each() method

我知道这不符合辅助函数要求,但我这样做的方法是使用 jQuery 的 $.each() 方法

var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
    function(i, v) {
        loginFormObject[v.name] = v.value;
    });

Then I can pass loginFormObject to my backend, or you could create a userobject and save() it in backbone as well.

然后我可以将 loginFormObject 传递给我的后端,或者您也可以创建一个用户对象并将其保存()到主干中。

回答by user3664916

I couldn't find an answer that would solve this:

我找不到可以解决这个问题的答案:

[{name:"Vehicle.Make", value: "Honda"}, {name:"Vehicle.VIN", value: "123"}]

This calls for this object:

这需要这个对象:

{Vehicle: {Make: "Honda", "VIN": "123"}}

So I had to write a serializer of my own that would solve this:

所以我必须自己编写一个序列化程序来解决这个问题:

function(formArray){
        var obj = {};
        $.each(formArray, function(i, pair){
            var cObj = obj, pObj, cpName;
            $.each(pair.name.split("."), function(i, pName){
                pObj = cObj;
                cpName = pName;
                cObj = cObj[pName] ? cObj[pName] : (cObj[pName] = {});
            });
            pObj[cpName] = pair.value;
        });
        return obj;
    }

Maybe it will help somebody.

也许它会帮助某人。

回答by tothemario

Trying to solve the same problem (validation without getting into complex plugins and libraries), I created jQuery.serializeJSON, that improves serializeArray to support any kind of nested objects.

试图解决同样的问题(无需进入复杂的插件和库进行验证),我创建了jQuery.serializeJSON,它改进了 serializeArray 以支持任何类型的嵌套对象。

This plugin got very popular, but in another project I was using Backbone.js, where I would like to write the validation logic in the Backbone.js models. Then I created Backbone.Formwell, which allows you to show the errors returned by the validation method directly in the form.

这个插件非常受欢迎,但在另一个项目中我使用了Backbone.js,我想在 Backbone.js 模型中编写验证逻辑。然后我创建了Backbone.Formwell,它允许您直接在表单中显示验证方法返回的错误。

回答by Mitar

If you do not care about repetitive form elements with the same name, then you can do:

如果您不关心具有相同名称的重复表单元素,那么您可以这样做:

var data = $("form.login").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));

I am using Underscore.jshere.

我在这里使用Underscore.js

回答by user1990497

If you are sending the form with JSON you must remove [] in the sending string. You can do that with the jQuery function serializeObject():

如果您使用 JSON 发送表单,则必须删除发送字符串中的 []。你可以用 jQuery 函数 serializeObject() 做到这一点:

var frm = $(document.myform);
var data = JSON.stringify(frm.serializeObject());

$.fn.serializeObject = function() {
    var o = {};
    //    var a = this.serializeArray();
    $(this).find('input[type="hidden"], input[type="text"], input[type="password"], input[type="checkbox"]:checked, input[type="radio"]:checked, select').each(function() {
        if ($(this).attr('type') == 'hidden') { //if checkbox is checked do not take the hidden field
            var $parent = $(this).parent();
            var $chb = $parent.find('input[type="checkbox"][name="' + this.name.replace(/\[/g, '\[').replace(/\]/g, '\]') + '"]');
            if ($chb != null) {
                if ($chb.prop('checked')) return;
            }
        }
        if (this.name === null || this.name === undefined || this.name === '')
            return;
        var elemValue = null;
        if ($(this).is('select'))
            elemValue = $(this).find('option:selected').val();
        else elemValue = this.value;
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(elemValue || '');
        } else {
            o[this.name] = elemValue || '';
        }
    });
    return o;
}

回答by Johnston

Here is what I use for this situation as a module (in my formhelper.js):

这是我在这种情况下用作模块的内容(在我的 formhelper.js 中):

define(function(){
    FormHelper = {};

    FormHelper.parseForm = function($form){
        var serialized = $form.serializeArray();
        var s = '';
        var data = {};
        for(s in serialized){
            data[serialized[s]['name']] = serialized[s]['value']
        }
        return JSON.stringify(data);
    }

    return FormHelper;
});

It kind of sucks that I can't seem to find another way to do what I want to do.

我似乎无法找到另一种方式来做我想做的事情,这有点糟糕。

This does return this JSON for me:

这确实为我返回了这个 JSON:

{"first_name":"John","last_name":"Smith","age":"30"}