开发者

Using the jQueryUI Datepicker to request a Rails view based on a specific date

I have a jQueryUI Datepicker on a user's profile page. When the user selects a date, rather than populate a text box with the date value, I'd like to immediately send a GET request to obtain statistics for that user on the date picked.

The URL would be something like this:

/users开发者_高级运维/1?date=20110905

And then my UsersController would look at params[date] and query the model for the appropriate date-based data.

The part I'm having trouble with is the JavaScript part. I'll need to hook into the jQueryUI Datepicker's onSelect event, but after I catch the event:

  1. How do I get the user ID from within the JavaScript code?
  2. How should I submit the GET request? I want a full page reload, so should I use window.location?


You can get the path of the URL with location.pathname, and you can reload the current page by assigning location.href to the URL you want to reload the page with. So, you would probably be looking at something like this:

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

        location = location.href + "?date=" + dateText;;
    }
});

Note, location.href gives you the entire URL, including querystring (for GET method) and hash, while location.pathname only gives you the path of URL. See the MDN documentation for the location object.


When processing ERB file, <% %> tags are processed first, on server. Then, the result is sent to the browser. So, you can inject ERB tags into your javascript, like this:

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

Then, you can use window.location to redirect, for example to index action:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜