2016-06-21 78 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 –