I want to POST a data as JSON to the controller
in javascript, the data is an array, for example, a = [1,2]
then I POST, say
$.post('user/data', {'data' : a})
in the user controller, I get the data from params.
However, when I retrieve params[:data], I got a hash:
{"0"=>1, "1"=>2}
rather then an array!
so I have to convert the hash into an array manually.
Is there a method to pass the exact array to the controller?
I had a similar problem recently. My fix was to send json content instead of the default form encoded.
I used
$.ajax(
{
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json'
}
);
In your example this could be done as:
$.ajax(
{
type: "POST",
url: 'user/data',
data: JSON.stringify({'data' : a}),
dataType: "json",
contentType: 'application/json'
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With