新手问题 今天碰到一个奇怪的关于 Rails 处理 Ajax 请求的问题

chiangdi · September 01, 2015 · Last by chiangdi replied at September 08, 2015 · 1294 hits

比如如果用 jQuery:

$.ajax({
url: "/menu_items",
method: "post",
data: {
    menu_items: [
        {"id":3,"content":"first"},
        {"id":4,"content":"first"},
        {"id":5,"content":"second"}
    ]
  }
})

然后后台就会看到:

Processing by MenuItemsController#create as */*
 Parameters: {"menu_items"=>{"0"=>{"id"=>"3", "content"=>"first"}, "1"=>{"id"=>"4", "content"=>"first"}, "2"=>{"id"=>"5", "content"=>"second"}}}

直接把数组变成了 Hash。。。 我折腾了半天然后在 SO 上找到这个答案才解决: http://stackoverflow.com/questions/6410810/rails-not-decoding-json-from-jquery-correctly-array-becoming-a-hash-with-intege/11697679#11697679

但是每次用JSON.stringify也太奇怪了吧,求问有没有什么简单的方法,以及为何这么奇怪。

menu_items = params["menu_items"].values

#1 楼 @lingzhuzi Thanks 我已经找到答案,是因为 jQuery 默认把 contentType 设置成了 'application/x-www-form-urlencoded'

You need to Sign in before reply, if you don't have an account, please Sign up first.