【问题标题】:Using the jQueryUI Datepicker to request a Rails view based on a specific date使用 jQueryUI Datepicker 根据特定日期请求 Rails 视图
【发布时间】:2011-09-05 15:01:07
【问题描述】:

我在用户的个人资料页面上有一个 jQueryUI Datepicker。当用户选择一个日期,而不是用日期值填充文本框时,我想立即发送一个GET 请求以获取该用户在所选日期的统计信息。

URL 应该是这样的:

/users/1?date=20110905

然后我的UsersController 会查看params[date] 并查询模型以获取适当的基于日期的数据。

我遇到问题的部分是 JavaScript 部分。我需要挂钩到 jQueryUI Datepicker 的 onSelect 事件,但在我捕捉到事件之后:

  1. 如何从 JavaScript 代码中获取用户 ID?
  2. 我应该如何提交GET 请求?我想要一个完整的页面重新加载,所以我应该使用window.location吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails jquery-ui datepicker


    【解决方案1】:

    您可以使用location.pathname 获取URL 的路径,并且可以通过将location.href 分配给您要重新加载页面的URL 来重新加载当前页面。所以,你可能会看到这样的东西:

    $('#datepicker').datepicker({
        onSelect: function(dateText, inst) {
            // location.pathname == '/users/1'
            var userId = location.pathname.split('/')[2];
            var dateText = ...
    
            location = location.href + "?date=" + dateText;;
        }
    });
    

    注意,location.href 为您提供了整个 URL,包括查询字符串(用于 GET 方法)和哈希,而location.pathname 只为您提供 URL 的路径。对于 location 对象,请参阅 the MDN documentation

    【讨论】:

    • 我可以完全删除 $.get 并只做 window.location = window.location.href + "?date=" + dateText; 吗?
    • 是的,你可以。不知何故,我错误地读到你想先做 AJAX。我会更新我的答案。
    【解决方案2】:

    在处理 ERB 文件时,首先在服务器上处理 标签。然后,将结果发送到浏览器。因此,您可以将 ERB 标签注入您的 javascript,如下所示:

    var user_id = <%= user.id %>;
    

    然后,您可以使用 window.location 进行重定向,例如索引操作:

    window.location = "<%= url_for :action => :index %>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多