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:
- How do I get the user ID from within the JavaScript code?
- How should I submit the
GET
request? I want a full page reload, so should I usewindow.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 %>";
精彩评论