3

我有两个字段 - 结束日期和开始日期(日期范围),我应该将它们传递给控制器​​并重新加载此页面。

这是我的代码:

    <%= form_tag(:controller => "financial_reports", :action => 'index', :method => 'post') do%>//maybe this line should be edited
   <%= datepicker_input "report","start_date", :dateFormat => "dd/mm/yy" %>
  <%= datepicker_input "report", "end_date", :dateFormat => "dd/mm/yy"%>
  <%end%>

并生成 HTML() :

  <form accept-charset="UTF-8" action="/financial_reports?method=post" method="post"...>
  <input id="report_start_date" name="report[start_date]" size="30" type="text" class="hasDatepicker"><script type="text/javascript">
<input id="report_end_date" name="report[end_date]" size="30" type="text" class="hasDatepicker"
    <input class="btn wide" id="btn-report" name="commit" type="submit" value="Run Report">
  </form>

我可以像这样获得 datepicker 值吗:

      $('#datepicker').datepicker({
    onSelect: function(dateText, inst) {
  $("input[name='report[start_date]']").val(dateText);
    }
});

我需要将它们传递给控制器​​并重新加载此页面,因为在此页面控制器中。

在这里我需要传递 JQUERY 值

    @financial_reports = current_user.financial_reports.where(:created_at => start_date.to_date..end_date.to_date)

或者我应该添加另一个动作或方法?你能建议什么?

4

2 回答 2

5

在我看来,使用 AJAX 而不是重新加载页面是最好的选择。您只是试图更新一些数据,没有理由执行整页刷新来做到这一点。我不是 RoR 爱好者,但似乎我们可以通过 -> 将数据发送到控制器

$.ajax({ 
  type: 'POST', 
  url: 'path/to/controller', 
  data: {'start_date' : $("input[name='report[start_date]']").val(), 
        'end_date' : $("input[name='report[end_date]']").val() }, 
  success: function(data){
    //data is whatever you RETURN from your controller. 
    //an array, string, object...something 
  } 
});`  

在您的 RoR 控制器中,您将通过执行...

var the_start = params[:start_date],
    the_end = params[:end_date]

Now you've got the data in your controller, you can apply the method to it. Then when you're ready to send the data back, return, print, whatever you do to send data to the page.

Also, RoR by default (when accessing a controller) expects to output a template to the view, since we just want to update data, you'll need to stop that default action using something like ->

render :layout => false

I hope this was helpful. I'm really not a RoR expert, but this is the method I used in the few times I dabbled.

Goodluck!

于 2012-08-06T14:51:33.470 回答
0

Rails 3 now has helpers to do exactly what you want. These are known as remote forms and links.

This blog post does a great job of explaining what they do and how they work.

于 2012-08-06T14:54:19.040 回答