doing a remote => true call with javascript

2019-08-11 19:24发布

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?

3条回答
我命由我不由天
2楼-- · 2019-08-11 19:56

This is how you do it:

$.rails.handleRemote($('<a>', { href: '/path', 'data-method': 'GET' }));

查看更多
Explosion°爆炸
3楼-- · 2019-08-11 20:01

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>
查看更多
啃猪蹄的小仙女
4楼-- · 2019-08-11 20:15

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
  });
});
查看更多
登录 后发表回答