在Rails 3中渲染静态部分到.ajax

Got*_*osh 3 ajax jquery partial ruby-on-rails-3

所以,我的Rails代码中有2个关注/取消关注表单.这是这样的

<%= form_tag( {:controller => 'profile', :action => 'unfollow_topic' }) do %>
  <%= hidden_field_tag :topic_id, @topic.id %>
  <button class="question_button" type="submit">Unfollow</button>
<% end %>
Run Code Online (Sandbox Code Playgroud)

还有这个:

<%= form_tag({:controller => 'profile', :action => 'follow_topic' }) do %>
 <%= hidden_field_tag :topic_id, @topic.id %>
 <button class="question_button" type="submit">Follow</button>
<% end %>
Run Code Online (Sandbox Code Playgroud)

然后我有这个javascript代码:

<script type="text/javascript">
  $(function(){
    $('#follow form').submit(function(e) {
      $.ajax({
        url: this.action,
        type: 'POST',
        data: $(this).serialize(),
        success: function(response){ $('#follow').html(response); }
      });
    return false;
    });
  });   
</script>
Run Code Online (Sandbox Code Playgroud)

我的问题是我如何从我的控制器返回适当的"跟随/取消关注"部分,以便将其替换为返回的响应.

我目前拥有的是这个,但它似乎不起作用:

  respond_to do |format|
    format.html { redirect_to('/' + topic.type + '/' + topic.uri) }
    format.js   { render :partial => 'unfollow_topic' }
  end
Run Code Online (Sandbox Code Playgroud)

但相反,如果渲染整个页面,我相信它实际上是对format.html而不是format.js的任何想法做出回应?

Jon*_*nny 5

JavaScript的:

  <script type="text/javascript">
      $(function(){
        $('#follow form').submit(function(e) {
          $.ajax({
            url: this.action,
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'html'
            success: function(response){ $('#follow').html(response); }
          });
        return false;
        });
      });   
    </script>
Run Code Online (Sandbox Code Playgroud)

控制器:

respond_to do |format|
    format.html  do
      if request.xhr?
        render :partial => 'unfollow_topic'
      else
        redirect_to('/' + topic.type + '/' + topic.uri)
      end
    end
end
Run Code Online (Sandbox Code Playgroud)