简体   繁体   English

Rails 3:“redirect_to”在 Ajax 调用后无法正常工作

[英]Rails 3: “redirect_to” doesn't work well after Ajax call

In my Rails 3 application user adds a new message to forum using Ajax:在我的 Rails 3 应用程序中,用户使用 Ajax 向论坛添加了一条新消息:

<%= form_tag("/forum/add_new_message", :remote => true) do %>
  <%= text_area_tag("new_message_area") %>
<% end %>

Here is my controller's code:这是我的控制器的代码:

def index
  @messages = Message.all
end

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

The problem is that after user adds a new message, redirect_to(:action => 'index') executed, but the page is not refreshed, ie I don't see the new message.问题是用户添加新消息后, redirect_to(:action => 'index')执行,但页面没有刷新,即我没有看到新消息。

Why?为什么?

The web browser is expecting some javascript to be executed after the ajax has been called. web 浏览器期望在调用 ajax 之后执行一些 javascript。 Your code should work when javascript is disabled in the browser.当 javascript 在浏览器中被禁用时,您的代码应该可以工作。

In the add_new_message method you should add:在 add_new_message 方法中,您应该添加:

respond_to do |format|
  format.html { redirect_to(:action => 'index') }
  format.js
end

Then some javascript in add_new_message.js.erb will be executed, so to redirect to the index, the code in add_new_message.js.erb should look like:然后 add_new_message.js.erb 中的一些 javascript 将被执行,因此要重定向到索引, add_new_message.js.erb 中的代码应该如下所示:

window.location = '<%= forums_path %>'; //or whatever other path

Although both the HTML and javascript do the same thing.尽管 HTML 和 javascript 做同样的事情。 Why is the ajax needed in the first place?为什么首先需要 ajax?

I'd be tempted to go for something like this in the controller:我很想在 controller 中使用 go 进行类似的操作:

def index
  @messages = Message.all
end

def add_new_message
  Message.create(:text => params[:new_message_area], ...)                 
  render js: %(window.location.pathname='#{messages_path}')
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM