简体   繁体   English

在会话中传递所选国家/地区的值(下拉列表),然后重新加载当前页面(路轨4)

[英]Pass value of selected country (dropdown) in session and then reload current page (Rails 4)

In my Rails app, I'm trying to ask the user in the footer which country he'd like to see (France/United States/Germany...) and then store this in session and reload the page he's currently on. 在我的Rails应用中,我试图问页脚中的用户他想看哪个国家(法国/美国/德国...),然后将其存储在会话中并重新加载他当前所在的页面。

Note that: I just want the current page to reload but I don't want to add a params in the URLs of my app(ie I don't want example.com/browser_country=France). 请注意:我只希望重新加载当前页面,但不想在应用程序的URL中添加参数(即,我不希望example.com/browser_country=France)。 I want them to stay as they are (example.com). 我希望他们保持原样(example.com)。

How can I do that? 我怎样才能做到这一点?

This is my code below but it's not working (i'm a Rails newbie): 这是我的下面代码,但是不起作用(我是Rails新手):

<footer class="footer">

    <small>
        MySuper Website <br/>
        <select name= "browser_country", :onchange => "location.href = '#{current_path}'"  >
           <option value="">Select Country</option>
              <option value="1">France</option>
              <option value="2">United States</option>
        </select>

    </small>

Here if the controller that loads the page (homepage)on /app/controllers/static_pages_controller.rb 如果是在/app/controllers/static_pages_controller.rb上加载页面(主页)的控制器

class StaticPagesController < ApplicationController

  def home        
  end

  def set_country_into_session
    session[:country] = :browser_country # i'm putting in session the country selected in the dropdown
  end       

end

You will need to add an ajax call to this process. 您将需要向该过程添加一个ajax调用。

# your js file
$(function() {
    $('select[name="browser_country"]').change(function() {
        $.ajax({
            url: 'static_pages/set_country_into_session',
            data: 'browser_country=' + this.value,
            success: function() {
                location.reload();
            }
        });
    });
});

# static_pages_controller.rb
def set_country_into_session
  session[:country] = params[:browser_country]

  render text => :ok
end 

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

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