开发者

:remote => true with url_for, How does one do this?

I am trying to make an entire div tag clickable. The code I am trying to use is below, and when I add the

:remote => true

bit it throws Too many args error, 2 for 1.

Code:

<div id="foo" onclick="wind开发者_运维知识库ow.location = '<%= url_for foo_controller_path(:someparam => @left), :remote => true %>'"></div>


url_for doesn't accept the :remote => true argument, it's usually the link_to method that you would send it to.

Is there a reason you can't make your <div> a link instead? For all intents and purposes it is functioning as a link, so you should mark it up as such, we call that semantic mark-up.

If you really wanted to do this it would probably be best to use jquery (or prototype, if that's your cup of tea) to perform the action unobtrusively... it makes it easier to do the ajax request too. Are you trying to update something on your page after the link is clicked, or just do nothing?

Also the 'window.location' is telling the javascript on the page to redirect. You wouldn't use that if you wanted to make the request remotely.

Using jquery you could do it like this if you want to stick with a div

%(function(){
  $('#foo').click(function(){
    $.get(
      url: $(this).data('request-path'),
      success: function(data){
        alert('success sir!  controller responded with ' + data);
      }
    );
  });
});

And use this in your view:

<div id='foo' data-request-path='<%= url_for foo_controller_path(:someparam => @left) %>'></div>

But if you changed it to a link tag you could do this instead...

= link_to("", url_for(foo_controller_path(:someparam => @left)), :remote => true, :id => 'foo')

And it ought to just work. Then you can style this link the way that you were trying to style your div tag.

This is more semantic and less code for you to worry about. If you need to update something in the dom afterwards you can add this jquery (if you're using jquery, and rails3):

$('#foo').bind('ajax:success', function(data){
  alert('successful request!  data was:  ' + data);
});

I didn't necessarily test all of this but it should be a good starting point... I'm not a big fan of putting onclick handlers into tags. It tends to work nicer when you bind events using jquery.

If you want to be able to do what i've described but you're in rails 2, you can get the rails3 jquery script from here: https://github.com/rails/jquery-ujs

Note that you'll also need that script if you're using rails 3 and want jquery instead of prototype (like me!). Rails 3.1 will come bundled with jquery instead of prototype I hear, by default.

And change the :remote => true in that url_for to "data-remote" => true (for rails 2, with rails 3 you can use the symbol syntax and it makes the 'data-remote' attribute for you.

Let me know if something didn't quite work or you need clarification. Or even if you hate my ideas alltogether :p

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜