开发者

Dynamic path in new.AjaxRequest with Rails

开发者 https://www.devze.com 2023-01-01 11:47 出处:网络
I was wondering if there\'s anyway to get a \'dynam开发者_JS百科ic path\' into a .js file through Ruby on Rails.

I was wondering if there's anyway to get a 'dynam开发者_JS百科ic path' into a .js file through Ruby on Rails.

For example, I have the following:

new Ajax.Request('/tokens/destroy/' + GRID_ID, {asynchronous:true, evalScripts:true, onComplete:function(request){load('26', 'table1', request.responseText)}, parameters:'token=' + dsrc.id + '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)})

The main URL is '/tokens/destroy/:id', however on my production server this app runs as a sub folder. So the URL for this ajax call needs to be '/qrpsdrail/tokens/destroy/:id'

The URL this is being called from would be /grids/1 or /qrpsdrail/grids/1

I could, of course, do ../../path -- but that seems a bit hackish. It is also dependent on the routing never changing, which at this stage I can't guarantee. I'm just interested in seeing what other solutions there might be to this problem.

Thanks in advance :)


Maybe a bit hackish solution, but i have a configuration-file like described here, and so you could do something like, inside a config.yml :

development:
  root: /

production:
  root: /qrpsdrail/

and when you build your Ajaxrequest, you could write

new Ajax.Request("#{AppConfig.root}tokens/destroy/' + ...

But it still looks like there should be a cleaner way to solve this ;)


you can use Dynamic path in new.AjaxRequest using javascript in rails

javascript

 function dynamic_ajax(GRID_ID)
  {
      new Ajax.Request("/tokens/destroy?"+GRID_ID, {asynchronous:true, evalScripts:true, onComplete:function(request){load('26', 'table1', request.responseText)}, parameters:'token=' + dsrc.id + '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)});
  }

html

<a href="javascript:void(0)" onclick="dynamic_ajax('1')">Grid Id 1 </a>
<a href="javascript:void(0)" onclick="dynamic_ajax('2')">Grid Id 2 </a>
<a href="javascript:void(0)" onclick="dynamic_ajax('3')">Grid Id 3 </a>


You can set the path as an attribute to your html object that initiates the ajax call. An example would be:

HTML

<a id='my_clicky_thing' href='#' rails_path='<%= tokens_destroy_path %>'>Click me</a>

JQuery

$('#my_clicky_thing').live('click', function(){
  var ajax_path = $(this).attr('rails_path');
  /* Do ajax stuff here with the path */
});

This would allow you to use the actual rails path in your .js files, as you do in your views.

(This code may not work, it is for the concept only)

0

精彩评论

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