输入数组在Rails参数中转换为散列

时间:2014-08-08 10:49:59

标签: ruby-on-rails parameter-passing

我在AJAX请求中发送一个数组:

$.ajax(
    {
        type: "POST",
        url: "http://192.168.0.15/calc",
        data: {
            "phone": phone,
            "points": [
                { "lat": 59.15234, "lon": 30.99 },
                { "lat": 59.15244, "lon": 30.99 },
                { "lat": 59.15254, "lon": 30.99 }
            ],
            "start_at": 1407249093,
            "certificate": "849840487484"
        },
        success: function(data) {
            alert('success');
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.statusCode());
            console.log(textStatus);
            console.log(errorThrown);
        }
    }
);

然后检查点:

params[:points].inspect

并查看哈希:

{
  "0"=>{"lat"=>"59.15234", "lon"=>"30.99"},
  "1"=>{"lat"=>"59.15244", "lon"=>"30.99"},
  "2"=>{"lat"=>"59.15254", "lon"=>"30.99"}
}

如何获取数组而不是散列(最好是最初,而不必将散列转换为数组)?

2 个答案:

答案 0 :(得分:0)

如果可以的话:

"points": [
    '{ "lat": 59.15234, "lon": 30.99 }',
    '{ "lat": 59.15244, "lon": 30.99 }',
    '{ "lat": 59.15254, "lon": 30.99 }'
]

现在这将被视为字符串数组,在解析时,您可以将其转换为哈希值进行解析。

告诉我这是否解决了您的问题。

修改

$.ajax({
  ..
  ..
  dataType: 'json',
  contentType: 'application/json',
  data : JSON.stringify({"points": [
     { "lat": 59.15234, "lon": 30.99 },
     { "lat": 59.15244, "lon": 30.99 },
     { "lat": 59.15254, "lon": 30.99 }]
  })
});

答案 1 :(得分:0)

解决方案

Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys)

只需添加内容类型并将其设置为contentType: 'application/json'

即可