Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

ajax - jQuery post to Rails

My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2

I have a form that shows multiple photos and comments for a user and I wish to implement inline commenting.

<div id="newsfeed">    
 <div> 
 <div class="photo_title">Summer 2011</div> 
 <div class="newsfeed_photo"> 
 <a href="..." /></a> 
 </div> 
 <textarea class="comment_box">Write a comment...</textarea>  
</div> 
<div> 
 <div class="comment_title">Seeing a movie</div> 
 <textarea class="comment_box">Write a comment...</textarea>  
</div> 

I want to submit an AJAX post upon the user hitting the enter key in the textarea field. Here's the javascript (incomplete) that I have so far

  $('#newsfeed').delegate('.comment_box', 'keydown', function (event){
    event.preventDefault();
    $.post('/sub_comments', ...);
  });

I'm using the delegate method because <div id='newsfeed'> contents could be replaced with another AJAX call. What I need is the syntax for jQuery post method assuming I need to pass some form params like say photo_id, etc. Assume that I have a way to access the values for the params, what's the syntax for the post call to creating params the way Rails expect them

Here's the standard Rails bits

sub_comments_controller.rb

  def new
    @sub_comment = SubComment.new

    respond_to do |format|
      format.html # new.html.erb
      format.js
    end
  end

Also I don't want to use the usual <%= form_for(@sub_comment, :remote => true) do |f| %> for each and every inline comment I could add. I have also taken a look at Ryan Bates's railscast but the code looks outdated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can setup your post to structure the data in any way as long as it is interpreted correctly on the rails end, but best practice is to have an object of 'model-name' with all the values.

Javascript

$.ajax({
    url: "/sub_comments",
    type: "POST",
    data: {subcomment: {
             field: val, 
             field2: val, etc... }},
    success: function(resp){ }
});

Rails

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...