2015-10-14 60 views
2

我有一个观点
index.html.erb - >
link_to "click me " , 'customers/index' , :remote => true让js.erb文件没有Ajax工作的Ruby on Rails的4

控制器 - >客户

def index 
end 

index.js.erb的

alert('in js file'); 

alert作品精绝。但是如果我不想制作ajax,并且每次加载客户/索引时我只想让js.erb文件工作,该怎么办?我是rails开发新手,我的问题可能很基本,但我找不到解决方案。我知道当我们需要特定类型时,我们指定了以下内容。但据我知道我的情况是differenct

respond_to do |format| 
format.js 
format.html 
end 

回答

1

你可以简单地将代码移动从index.js.erbindex.html.erb

如果你想分开保存它,那么你可以将js代码移动到一个局部,并将其渲染到index.html.erb之内。请参阅文档here

更新

如何使用部分做到这一点:

  1. 创建_yourpartial.js.erb与JS代码填写
  2. 要渲染内 'index.html.erb' 代码补充一点:<%= render partial: 'yourpartial', formats: [:js] %>

(但是当然你仍然需要围绕js代码的脚本标记)

+0

难道你不喜欢'js.erb'部分的美丽吗? :) – nsave

+0

我的意思是创建'_yourpartial.js.erb'并将其呈现在'index.html.erb'内 – nsave

+0

@ImranNaqvi,你检查了我的更新答案吗?如果它看起来像一个文本,那么你只是忘了添加'script'标签 – nsave

-1

我会尽力帮助你。你可以把你的ajax放入你的application.js。为了使它干净,你必须创建一个文件准备好的功能。当页面已经完成加载时,文档就绪功能将被激活。

$(document).ready(function() { 
    callAjaxCustomerIndex(location.pathname); 
}); 

function callAjaxCustomerIndex(current_url) { 
    if (current_url == "/customers") 
    $.ajax({ 
     url: "/customers", 
     async: false, 
     method: "GET", 
     data: { "place_id" : place["place_id"] }, 
     success: function(data){ 
       alert('success'); 
      } 
     }); 
     infoWindow.open(map, marker); 
     buildIWContent(place); 
    }); 
} 

location.pathname是“客户”时,将发送此ajax请求。我希望这对你有所帮助。

+0

我想你没有注意到这个问题。我清楚地表明,我希望js.erb在没有** ajax的情况下工作 – ImranNaqvi