提交表单时将JavaScript对象添加到表单数据

时间:2018-08-23 12:33:49

标签: javascript jquery json

用户可以选择在表单中执行多个操作,提交表单后,需要在表单中添加JavaScript对象。我尝试了多种方法,以达到服务器数据[Object object]

JavaScript对象

var damageitems = {'5b3b43285d57025915000002':
                  {action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
                  }

我尝试过的脚本

$( "form" ).submit(function( event ) {
        event.preventDefault();
        url = $(this).attr( "action" );
        var postData = $(this).serializeArray();
        postData.push({name: 'damage_items', value: damage_items});
        $.post(url, postData, function(){});
    });

在服务器中达到的值

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"uztc+G0fyTb8wH7D6HZAslTfxuJvFLP3UunjiRjWylk=", "damage_items"=>"[object Object]", "action"=>"batch_update", "controller"=>"damage_items", "claim_id"=>"5b3b41415d57026665000001"}

我的目标是将值提交为正常提交而不是ajax, js变量中的值通过键damage_items作为哈希值到达服务器。 不喜欢将其添加到表单控件值中然后提交的方法

2 个答案:

答案 0 :(得分:1)

将脚本更新为以下内容即可达到目的

$( "form" ).submit(function( event ) {
    event.preventDefault();
    url = $(this).attr( "action" );
    var postData = $(this).serializeArray();
    postData.push({name: 'damage_items', value: JSON.stringify(damage_items)});
    $.post(url, postData, function(){});
});

当您尝试以表格形式存储数据时,如果它还不是字符串,则使用toString方法将其转换为字符串。 Object的toString方法返回[object Object],这就是为什么要获取它。

将其转换为JSON字符串可以防止这种情况。

答案 1 :(得分:1)

最好的方法是将JavaScript对象文字转换为JSON(请参见区别here)。因为机器很容易解析和生成,并且大多数服务器端语言都有解析它的方法。同样在http请求中(例如ajax),我们必须发送字符串。

幸运的是,我们在js中有一个方法可以做到这一点,并且正在使用JSON.stringify()和使用JSON.parse()

将JSON转换为JavaScript Object Literal的方法。

然后,在您的代码中:

//JavaScript Object Literal
var damageitems = {'5b3b43285d57025915000002':
                  {action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
                  }


damageitems = JSON.stringify(damageitems);


//JSON - It is easy for machines to parse and generate
// we could put this in a request because it's a string,
console.log(damageitems);