每次我想将带有jQuery的JSON对象数组发布到Rails时,我都会遇到这个问题.

"shared_items"=>"[{\"entity_id\":\"253\",\"position\":1},{\"entity_id\":\"823\",\"position\":2}]"

But if I just send the array it as the data of the AJAX call I get:

"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}

Whereas if I just send a plain array it works:

"shared_items"=>["entity_253"]

为什么Rails要将数组更改为那个奇怪的散列?我想到的唯一原因是Rails无法正确理解内容,因为这里没有类型(有没有办法在jQuery调用中设置它?):

Processing by SharedListsController#create as 

Thank you!

Update: 我将数据作为数组发送,而不是字符串,并且该数组是使用.push()函数动态创建的.try 使用$.post$.ajax,结果相同.

推荐答案

In case someone stumbles upon this and wants a better solution, you can specify the "contentType: 'application/json'" option in the .ajax call and have Rails properly parse the JSON object without garbling it into integer-keyed hashes with all-string values.

So, to summarize, my problem was that this:

$.ajax({
  type : "POST",
  url :  'http://localhost:3001/plugin/bulk_import/',
  dataType: 'json',
  data : {"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]}
});

导致Rails解析如下内容:

Parameters: {"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}}

whereas this (NOTE: we're now stringifying the javascript object and specifying a content type, so rails will know how to parse our string):

$.ajax({
  type : "POST",
  url :  'http://localhost:3001/plugin/bulk_import/',
  dataType: 'json',
  contentType: 'application/json',
  data : JSON.stringify({"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]})
});

results in a nice object in Rails:

Parameters: {"shared_items"=>[{"entity_id"=>"253", "position"=>1}, {"entity_id"=>"823", "position"=>2}]}

This works for me in Rails 3, on Ruby 1.9.3.

Jquery相关问答推荐

当我使用 OwlCarousel 时,没有任何显示

多个 AJAX 调用;获取所有失败的呼叫

在 CSS3 或 jQuery 中将元素的宽度从 0% 设置为 100% 动画,它和它的包装器只需要它们需要的宽度,没有预先设置的宽度

AngularJS 中的 ScrollTo 函数

jQuery 与 javascript?

如何在数据表中显示空数据消息

在 JavaScript 中解析 URL

Chart.js 中饼图的点击事件

禁用 Android 网页中输入焦点的zoom

当ID包含方括号时按ID查找DOM元素?

jQuery getJSON 将结果保存到变量中

按值对 Html Select 的选项进行排序的最有效方法是什么,同时保留当前选定的项目?

聚焦 时防止 iphone 默认键盘

使用 JQuery 获取触发事件的元素的类

Jquery:如何判断元素是否具有某些 css 类/样式

禁用 jquery Select 的下拉菜单

jquery分别绑定双击和单击

使用 jQuery 获取选中复选框的值

只绑定一次事件

在 Javascript/jQuery 中,(e) 是什么意思?