jQuery 将序列化表单的数据转换为 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23287067/
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-27 02:14:17  来源:igfitidea点击:

Converting serialized form's data to json object

jqueryasp.net-mvcjsonserialization

提问by Null Reference

I have a cshtml like the following

我有一个像下面这样的 cshtml

@using (Html.BeginForm("Save", "Plans", FormMethod.Post, new { @class = "form-horizontal", id = "floorplan-form" }))
{
            @Html.TextBoxFor(m => m.FloorPlan.Name, new { placeholder = "Enter text", @class = "form-control" })

            @Html.DropDownListFor(m => m.FloorPlan.GroupId, new SelectList(Model.FloorPlanGroups, "Id", "Name"))             
}

In my javascript(in a separate javascript file), I'm trying to serialize this form and convert it into a JSON object.

在我的 javascript(在一个单独的 javascript 文件中)中,我试图序列化这个表单并将其转换为一个 JSON 对象。

var formData = $("#floorplan-form").serialize();
console.info(formData);

prints out

打印出来

FloorPlan.Name=Test&FloorPlan.GroupId=15 

And

var formData = $("#floorplan-form").serializeArray();
console.info(formData);

gives me:

给我:

Screen capture

屏幕截图

I have tried doing this

我试过这样做

var formData = JSON.parse($("#floorplan-form").serializeArray());

But I get this error:

但我收到此错误:

Uncaught SyntaxError: Unexpected token o 

回答by Hitesh Siddhapura

Change your statement

改变你的说法

var formData = JSON.parse($("#floorplan-form").serializeArray());

with

var formData = JSON.stringify(jQuery('#frm').serializeArray()); // store json string

or

或者

var formData = JSON.parse(JSON.stringify(jQuery('#frm').serializeArray())) // store json object

回答by BITS_Python

Use the code below!!!

使用下面的代码!!!

    var data = $("form").serialize().split("&");
    console.log(data);
    var obj={};
    for(var key in data)
    {
        console.log(data[key]);
        obj[data[key].split("=")[0]] = data[key].split("=")[1];
    }

    console.log(obj);

回答by Moh .S

function jQFormSerializeArrToJson(formSerializeArr){
 var jsonObj = {};
 jQuery.map( formSerializeArr, function( n, i ) {
     jsonObj[n.name] = n.value;
 });

 return jsonObj;
}

Use this function. This will work only with jquery.

使用此功能。这仅适用于 jquery。

var serializedArr = $("#floorplan-form").serializeArray();

var properJsonObj = jQFormSerializeArrToJson(serializedArr);

回答by Willian Ray

You can use this for make a json with all fields of form.

您可以使用它来制作包含所有表单字段的 json。

Jquery example:

jQuery 示例:

$('form').serializeArray().reduce(function(accumulator,currentValue, currentIndex){
    if(currentIndex === 1){
        var json = {};
        json[accumulator.name] = accumulator.value;
        return json;
    }
    accumulator[currentValue.name] = currentValue.value;
    return accumulator;
});

Pure JavaScript with FormData:

带有 FormData 的纯 JavaScript:

var formdata = new FormData(document.querySelector('form'));
var getJsonFromFormData = (formData) => {
    var json = {};    
    for (item of formData.keys()){
        json[item] = formData.get(item);
    }
     return json;
}
var json = getJsdonFromFormData(formdata);

回答by synthet1c

A modern interpretation. babel stage-2 preset is required to compile the object spread operator

现代诠释。需要 babel stage-2 预设来编译对象扩展运算符

// serializeToJSON :: String -> JSON
const serializeToJSON = str => 
  str.split('&')
    .map(x => x.split('='))
    .reduce((acc, [key, value]) => ({
      ...acc,
      [key]: isNaN(value) ? value : Number(value)
    }), {})

console.log(
  serializeToJSON('foo=1&bar=2&baz=three')
)

回答by Raphael Monteiro Nunes

You can use: jquery.serializeToJSON- https://github.com/raphaelm22/jquery.serializeToJSONIts is prepared to work with forms ASP MVC

您可以使用:jquery.serializeToJSON- https://github.com/raphaelm22/jquery.serializeToJSON它准备使用表单 ASP MVC