jQuery发布到Rails
我的设置:Rails 3.0.9,Ruby 1.9.2,jQuery 1.6.2
我有一个表单,为用户显示多张照片和评论,我希望实现内联评论。
Seeing a movie
我想在用户点击textarea字段中的回车键时提交一个AJAXpost。 这是我到目前为止的javascript(不完整)
$('#newsfeed').delegate('.comment_box', 'keydown', function (event){ event.preventDefault(); $.post('/sub_comments', https://stackoverflow.com/questions/7237720/jquery-post-to-rails/...); });
我正在使用delegate
方法,因为
内容可以用另一个AJAX调用替换。 我需要的是jQuery post
方法的语法,假设我需要传递一些forms参数,比如说photo_id
等等。假设我有办法访问params的值,那么post
调用创建params的语法是什么Rails期待他们
这是标准的Rails位
sub_comments_controller.rb def new @sub_comment = SubComment.new respond_to do |format| format.html # new.html.erb format.js end end
另外我不想使用通常的 true) do |f| %>
true) do |f| %>
我可以添加的每个内联评论。 我还看了看Ryan Bates的railscast,但代码看起来已经过时了。
只要在rails端正确解释数据,您就可以设置post以任何方式构建数据,但最佳做法是使用具有所有值的’model-name’对象。
使用Javascript
$.ajax({ url: "/sub_comments", type: "POST", data: {subcomment: { field: val, field2: val, etc... }}, success: function(resp){ } });
轨道
def create @sub_comment = SubComment.new params['subcomment'] if @sub_comment.save render :json => { } # send back any data if necessary else render :json => { }, :status => 500 end end
Interesting Posts