2016-06-21 32 views
1

如何在javascript中更改视图的变量值。我的意思是,当我从下拉表中选择四月份时,只会显示四月份的数据,而当前表格数据会消失并刷新。我该怎么做?帮我
我的JS如何在js of rails中更改视图的可视化

:javascript 
    var updateMonth = function(){ 
     var month_id = $("#select_other_month").val(); 
     console.log(month_id) 
    } 

这是我的选择标签(下拉)

%select{:name => "options", :id=>"select_other_month",:onchange=>"updateMonth()"} 
      %option.placeholder{:disabled => "", :selected => "", :value => ""} see other months 
      %option{:value => "0"} this month 
      [email protected]_month - 1.month 
      %option{:value => "5"}=a.strftime('%Y-%m') 
      [email protected]_month - 2.month 
      %option{:value => "4"}=b.strftime('%Y-%m') 
      [email protected]_month - 3.month 
      %option{:value => "3"}=c.strftime('%Y-%m') 
      [email protected]_month - 4.month 
      %option{:value => "2"}=d.strftime('%Y-%m') 
      [email protected]_month - 5.month 
      %option{:value => "1"}=e.strftime('%Y-%m') 

和我的表看起来像这样

.table{:id=>"time_table"} 
     %table{:border=>"1"} 
      %thead 
       %tr 
        %th No 
        %th Name 
        -(@[email protected]_end_of_month).each do |day| 
         -if (day.saturday? || day.sunday?)==false 
          %th=day.strftime("%d") 
        %th Total days 
        %th Total time 

我想改变我的@xmonth从vairable JS
注意:@this_month = Date.today

+0

你想从服务器获取新的数据并填充? – Kumar

+0

是的,我是。我现在应该怎么做? –

回答

1
var updateMonth = function(){ 
    var month_id = $("#select_other_month").val(); 
    $.ajax({ 
    url: '/your_controller/its_method', //make sure to add this path to routes file 
    data: { 
     month_id: month_id 
    }, 
    success: function(response){ 
     $("#target_area").html(response); 
    }, 
    error: function(error_res){ 
     console.log(error_res); 
    } 
    }); 
} 

在视图文件中添加一个id,所以我们可以用新的反应,我们得到

%thead{:id => "target_area"} 
    %tr 
    %th No 
    %th Name 
    ... 

在你的控制器

class YourController 
    def your_method 
    month_id = params[:month_id] 
    #update your @xmonth by month_id 
    #your new information should be inside @xmonth object 
    respond_to do |format| 
     format.html {render partial: 'your_controller/your_method/your_partial.haml.erb' } 
    end 
    end 
end 

与创建您部分文件_your_partial.haml.erb替换其内容需要更换的内容

%tr 
    %th No 
    %th Name 
    -(@[email protected]_end_of_month).each do |day| 
    -if (day.saturday? || day.sunday?)==false 
    %th=day.strftime("%d") 
    %th Total days 
    %th Total time 

当您获得成功响应时,部分的内容将在您的视图中被替换为#target_area的内容。请参阅updateMonth函数。

希望这可以帮助

+0

谢谢你回答我的问题。但是我的建议遇到了问题。错误信息在我的问题上。 –

+0

@NeoTeo在'format.html'中渲染部分内容时不要使用'_',因为它会自动为您添加它。 – Kumar

+0

它的工作原理!感谢您的巨大建议:D –