简体   繁体   English

输入数组在Rails参数中转换为哈希

[英]Input array is converted to hash in Rails params

I am sending an array in AJAX request: 我在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);
        }
    }
);

Then inspect points: 然后检查要点:

params[:points].inspect

and see a hash: 并看到一个哈希:

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

How to get an array instead of hash (preferably initially, without having to convert the hash to array)? 如何获取数组而不是哈希(最好是最初,而不必将哈希转换为数组)?

If you can then do: 如果可以的话:

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

Now this will be considered as array of strings and when parsing you can convert it to hash to parse. 现在,这将被视为字符串数组,并且在解析时可以将其转换为哈希以进行解析。

Tell me if this solves your issue. 告诉我这是否可以解决您的问题。

EDIT 编辑

$.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 }]
  })
});

solution here 解决方案在这里

Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys) Rails无法从jQuery正确解码JSON(数组变成带有整数键的哈希)

simply you need to add the content type and set it to contentType: 'application/json' 只需添加内容类型并将其设置为contentType: 'application/json'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM