如何在javascript中更改视图的变量值。我的意思是当我从下拉列表中选择April时,只会显示4月份的数据和当前表格数据将会消失并刷新。我该怎么做?帮我
我的JS
: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
-a=@this_month - 1.month
%option{:value => "5"}=a.strftime('%Y-%m')
-b=@this_month - 2.month
%option{:value => "4"}=b.strftime('%Y-%m')
-c=@this_month - 3.month
%option{:value => "3"}=c.strftime('%Y-%m')
-d=@this_month - 4.month
%option{:value => "2"}=d.strftime('%Y-%m')
-e=@this_month - 5.month
%option{:value => "1"}=e.strftime('%Y-%m')
我的表看起来像这样
.table{:id=>"time_table"}
%table{:border=>"1"}
%thead
%tr
%th No
%th Name
-(@xmonth.at_beginning_of_month..@xmonth.at_end_of_month).each do |day|
-if (day.saturday? || day.sunday?)==false
%th=day.strftime("%d")
%th Total days
%th Total time
我想从JS改变我的@xmonth vairable
注意:@this_month = Date.today
答案 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
-(@xmonth.at_beginning_of_month..@xmonth.at_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函数。
希望这有帮助