Rails 3:"redirect_to"在Ajax调用后不能正常工作

Mis*_*hko 1 ajax ruby-on-rails ruby-on-rails-3

在我的Rails 3应用程序中,用户使用Ajax向论坛添加了一条新消息:

<%= form_tag("/forum/add_new_message", :remote => true) do %>
  <%= text_area_tag("new_message_area") %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码:

def index
  @messages = Message.all
end

def add_new_message
  Message.create(:text => params[:new_message_area], ...)                 
  redirect_to(:action => 'index')
end
Run Code Online (Sandbox Code Playgroud)

问题是用户添加新消息后redirect_to(:action => 'index')执行,但页面没有刷新,即我没有看到新消息.

为什么?

Sup*_*o93 5

Web浏览器期望在调用ajax之后执行一些javascript.在浏览器中禁用javascript时,您的代码应该可以正常工作.

在add_new_message方法中,您应该添加:

respond_to do |format|
  format.html { redirect_to(:action => 'index') }
  format.js
end
Run Code Online (Sandbox Code Playgroud)

然后将执行add_new_message.js.erb中的一些javascript,因此要重定向到索引,add_new_message.js.erb中的代码应如下所示:

window.location = '<%= forums_path %>'; //or whatever other path
Run Code Online (Sandbox Code Playgroud)

虽然HTML和JavaScript都做同样的事情.为什么首先需要ajax?