doing a remote => true call with javascript

僤鯓⒐⒋嵵緔 提交于 2019-12-12 17:26:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!