带有Rails的new.AjaxRequest中的动态路径

时间:2010-05-27 15:50:30

标签: ruby-on-rails ajax prototypejs

我想知道是否有通过Ruby on Rails将“动态路径”转换为.js文件。

例如,我有以下内容:

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)})

主URL是'/ tokens / destroy /:id',但是在我的生产服务器上,此应用程序作为子文件夹运行。所以这个ajax调用的URL必须是'/ qrpsdrail / tokens / destroy /:id'

从中调用此URL将是 / grids / 1或/ qrpsdrail / grid / 1

当然,我可以做../../path - 但这看起来有点像hackish。它还取决于路由永不改变,在这个阶段我无法保证。 我只是想看看这个问题可能有什么其他解决方案。

提前致谢:)

3 个答案:

答案 0 :(得分:1)

也许有点hackish解决方案,但我有一个像here描述的配置文件,所以你可以在config.yml内做一些事情:

development:
  root: /

production:
  root: /qrpsdrail/

当你构建Ajaxrequest时,你可以编写

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

但看起来仍然应该有一种更清洁的方法来解决这个问题;)

答案 1 :(得分:0)

您可以在rails

中使用javascript在new.AjaxRequest中使用动态路径

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>

答案 2 :(得分:0)

您可以将路径设置为启动ajax调用的html对象的属性。一个例子是:

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 */
});

这将允许您在.js文件中使用实际的rails路径,就像在视图中一样。

(此代码可能不起作用,仅适用于概念)

相关问题