问题
Is there a way to have the same behavior as a link_to ... remote=> true
with javascript?
maybe it's not necessary -
I have a div with the user's name and picture in it.
I want to have the entire div to react to a click and go to the method (users#show
for example) as if it were a link_to.
The problem with link_to is that it creates a href
, making the text linkable etc.
Also, I can't seem to use it to make the whole div clickable, only the text.
In an attempt to explain myself more -
If link_to
corresponds to window.location
in javascript
what is link_to
with :remote=>true
in javascript?
回答1:
This is how you do it:
$.rails.handleRemote($('<a>', { href: '/path', 'data-method': 'GET' }));
回答2:
I'm not entirely familiar with Rails, but after reading the description of the method, it sounds like you're simply doing an ajax call. It's funny how much Rails abstracts this concept.
If you're using a library like jQuery, doing an ajax call on click is very simple:
$('element').click(function(e){
$.get('url', function action(){
// Do stuff
});
});
回答3:
To have a DIV work with remote=>true, after inspecting jquery-ujs carefully, it would seem you could wrap the DIV which you want clickable around a FORM like so:
<form action="/users" method="POST" data-remote="true">
<div onclick="$(this.parentNode).trigger('submit.rails');">Remote Request</div>
<input type="submit" style="display:none" />
</form>
来源:https://stackoverflow.com/questions/14495372/doing-a-remote-true-call-with-javascript