rails ujs以阵列格式发送formdata而不是基于索引的对象
我正在尝试使用FormData和Rails UJ将数据发送到我的Rails Server。前端JS代码看起来像这样:
Rails.ajax({
url: "/reset-cart",
type: "post",
data: new FormData(this.formTarget),
success: function(data) { console.log('success') },
error: function(data) { console.log('error') }
})
`Object.fromEntries(new FormData(this.formTarget))` returns
{
cart[cart_items_attributes][0][product_id]: "210"
cart[cart_items_attributes][0][quantity]: "4"
cart[cart_items_attributes][1][product_id]: "12"
cart[cart_items_attributes][1][quantity]: "4"
}
在我的导轨控制器中,我接收到以这种方式形成的数据:
#<ActionController::Parameters {"cart"=>{"cart_items_attributes"=>{"0"=>{"product_id"=>"210", "quantity"=>"4"}, "1"=>{"product_id"=>"12", "quantity"=>"4"}}}, "controller"=>"carts", "action"=>"reset"} permitted: false>
我希望数据看起来更像:
{
"cart"=> {
"cart_items_attributes"=> [
{
"product_id"=>"210",
"quantity"=>"4"
},{
"product_id"=>"12",
"quantity"=>"4"
}
]
}
}
其中cart_items_attributes
是哈希的数组。是否有一种方法可以通过更改我在rails.ajax
函数中发送数据的方式来实现这一目标,或者我必须在控制器中重新格式化我在params hash中收到的数据的自定义方法
I am trying to send data to my rails server using formData and Rails ujs. The Front end js code looks like this :
Rails.ajax({
url: "/reset-cart",
type: "post",
data: new FormData(this.formTarget),
success: function(data) { console.log('success') },
error: function(data) { console.log('error') }
})
`Object.fromEntries(new FormData(this.formTarget))` returns
{
cart[cart_items_attributes][0][product_id]: "210"
cart[cart_items_attributes][0][quantity]: "4"
cart[cart_items_attributes][1][product_id]: "12"
cart[cart_items_attributes][1][quantity]: "4"
}
In my rails controller I receive data formated this way :
#<ActionController::Parameters {"cart"=>{"cart_items_attributes"=>{"0"=>{"product_id"=>"210", "quantity"=>"4"}, "1"=>{"product_id"=>"12", "quantity"=>"4"}}}, "controller"=>"carts", "action"=>"reset"} permitted: false>
I'd like the data to look more like :
{
"cart"=> {
"cart_items_attributes"=> [
{
"product_id"=>"210",
"quantity"=>"4"
},{
"product_id"=>"12",
"quantity"=>"4"
}
]
}
}
where cart_items_attributes
is a array of hash. Is there a way to achieve that by changing the way I send data in the Rails.ajax
function or do I have to writte a custom method in the controller to reformat the data I receive in the params hash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经使用了这个jQuery插件来做到这一点,但是我还没有找到任何人做香草的示例。
https://github.com/marioizquierdo/jquery/jquery.serialializejson
I’ve used this jQuery plugin to do exactly this, I haven’t found an example of anyone doing it vanilla though.
https://github.com/marioizquierdo/jquery.serializeJSON