将jQuery变量分配给Rails会话变量

时间:2016-05-25 10:55:54

标签: jquery ruby-on-rails session assign

我有一个简单的选择框,包含年份和值 像这样

<div id="year_selection_area" class="controls text-center">
  <select class="form-control " name="Legislation year" id="dueYear">
    <OPTION VALUE='2017' >2017</OPTION>
    <OPTION VALUE='2016' >2016</OPTION>
    <OPTION VALUE='2015'>2015</OPTION>
    <OPTION VALUE='2014' >2014</OPTION>
    <OPTION VALUE='2013'>2013</OPTION>
    <OPTION VALUE='2012' >2012</OPTION>
    <OPTION VALUE='2011'>2011</OPTION>
    <OPTION VALUE='2010'>2010</OPTION>
    <OPTION VALUE='' DISABLED>MORE YEARS ADDED SOON</OPTION>
  </select>
</div>

我也在开始时通过混合使用jQuery和rails来分配

<% if session[:year_browsing]==nil%>
  <% session[:year_browsing] = 2016%>
<% else %>
  <%= session[:year_browsing] %>
<%end%>
<script  type="text/javascript">
  jQuery(document).ready(function($) {
    $('.form-control option[value=<%= session[:year_browsing] %>]').attr('selected','selected');
  });

但是我需要根据用户点击次数更改会话变量 我尝试了一个if / else语句,但是一旦进入更改函数

,它就会执行所有ruby
$( ".form-control" ).change(function() {
  alert( $(".form-control").val());
  var selectedValue = $(".form-control").val();

  if ( selectedValue=='2017'){
    <% session[:year_browsing] = 2017 %>
  }
  else if ( selectedValue=='2016'){
    <% session[:year_browsing] = 2016 %>
  }
  else if ( $(".form-control").val()=='2015'){
    <% session[:year_browsing] = 2015 %>
  }
  else if ( $(".form-control").val()=='2014'){
    <% session[:year_browsing] = 2014 %>
  }
  else if ( $(".form-control").val()=='2013'){
    <% session[:year_browsing] = 2013 %>
  }
  else if ( $(".form-control").val()=='2012'){
    <% session[:year_browsing] = 2012 %>
  }
  else if ( $(".form-control").val()=='2011'){
    <% session[:year_browsing] = 2011 %>
  }
  else if ( $(".form-control").val()=='2010'){
    <% session[:year_browsing] = 2010 %>
  }
  else{
    <% session[:year_browsing] = 0 %>
  }
});

1 个答案:

答案 0 :(得分:3)

非常感谢Sebin(https://stackoverflow.com/users/1684772/sebin

我最终选择使用此代码将其存储在浏览器存储中

<script  type="text/javascript">
  jQuery(document).ready(function($) {
    var myVar = localStorage['myKey'] || '2016';
    $('.form-control option[value='+myVar+']').attr('selected','selected');
  });

  $( ".form-control" ).change(function() {
    alert( $(".form-control").val()) ;
    var selectedValue = $(".form-control").val();
    localStorage['myKey'] = selectedValue;
  });
</script>