I have this JS object:
obj = {id: 80, attr_name: "avatar", style: "small", upload_path: null}
I then post this object as params with AJAX to the controller. What I would like to see in the params is something like this:
params[:attachment][:id] = 80
params[:attachment][:attr_name] = "avatar"
and so on and on...
So on the JS side I created an object that holds attachment params:
{attachment:obj}
While I do get params[:attachment] the result it [object Object].
How can I turn my JS object into an array inside params[:attachment]?
Thanks,
-
How are you sending the Post request? are you perhaps doing it via jQuery's $.post?jlstr– jlstr2013年11月28日 18:47:44 +00:00Commented Nov 28, 2013 at 18:47
2 Answers 2
One way is, instead of {attachment: obj} to make it like so:
postData = {
"attachment[id]": obj.id,
"attachment[attr_name]": obj.attr_name
}
Another method is to use stringify the JS object as JSON, and JSON.parse it on the other side.
However jQuery.ajax, when you pass an object to the "data" parameter, ought to send it along just fine as is. See: Post an object as data using Jquery Ajax
Comments
Assuming you're using jQuery (which is Rails default), this would work:
<h1>TEST</h1>
<script type="text/javascript">
$(function() {
params = {};
params.attachment = {};
params.attachment.id = 80;
$.post( "/the_action", params, function(data) {
alert("response");
}, "json");
});
</script>
You may verify this in the controller like this:
class MainController < ApplicationController
respond_to :html, :json
def index
end
def the_action
print params
puts params[:attachment][:id]
render nothing: true
end
end
That should print the data in the format you desire.
3 Comments
Explore related questions
See similar questions with these tags.