javascript ajax调用后Rails 4页面重新加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18882594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4 page reload after ajax call
提问by Powertoaster
I have an application that displays a large number of informational pages based on a location that I store in the session variable.
我有一个应用程序,它根据我存储在会话变量中的位置显示大量信息页面。
I am using a single select in a partial shared between varied pages from other controllers.
我在来自其他控制器的不同页面之间共享的部分中使用单个选择。
_location_select.html.erb
_location_select.html.erb
<%= select_tag(:location, options_for_select(Location.all.order('name ASC').collect { |l| [l.name, l.id] }, [session[:location]||'']), include_blank: true) %>
This makes an ajax call to:
这使 ajax 调用:
locations_controller.rb
location_controller.rb
class LocationsController < ApplicationController
def select
session[:location] = params[:value]
render js: ''
end
end
Here is my coffescript:
这是我的咖啡稿:
home.js.coffee
home.js.coffee
$ ->
$('#location').change ->
$.get '/location/select', {value: $('option:selected', this).val()}
All of this code works great, but I need to have the page reload after the ajax call is complete, It would be too complicated to have the controller return the updated html since the location select will appear on such a large number of pages.
所有这些代码都很好用,但是我需要在 ajax 调用完成后重新加载页面,让控制器返回更新的 html 太复杂了,因为位置选择将出现在如此大量的页面上。
I have tried adding success:, and error: call back functions to the ajax call and have also played around with ajaxStop. I can get the ajax call to work or the page reload to work but cannot figure out the way to get both.
我曾尝试将成功:和错误:回调函数添加到 ajax 调用中,并且还尝试了 ajaxStop。我可以让 ajax 调用工作或页面重新加载工作,但无法找出同时获得两者的方法。
I have tried adding:
我试过添加:
$(document).ajaxStop(function(){
window.location.reload();
});
Where do I put location.reload() or is there a better way?
我把 location.reload() 放在哪里还是有更好的方法?
FYI, I am not using turbolinks in this app.
仅供参考,我没有在这个应用程序中使用 turbolinks。
回答by Ayman
locations_controller.rb
location_controller.rb
class LocationsController < ApplicationController
def select
session[:location] = params[:value]
respond_to do |format|
format.js {}
end
end
end
views/locations/select.js
视图/位置/select.js
window.location.reload();