【问题标题】:Make js.erb file to work without ajax Ruby on Rails 4使 js.erb 文件在没有 ajax 的情况下工作 Ruby on Rails 4
【发布时间】:2015-10-14 12:49:21
【问题描述】:

我有意见
index.html.erb ->
link_to "click me " , 'customers/index' , :remote => true .

控制者 -> 客户

def index
end

index.js.erb

alert('in js file');

alert 工作得很好。但是如果我不想制作 ajax 而我只想让 js.erb 文件在每次加载客户/索引时工作。我是 rails 开发的新手,我的问题可能非常基本,但我找不到解决方案。我知道我们在需要特定类型时指定以下内容。但据我所知,我的情况不同

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

【问题讨论】:

    标签: ruby-on-rails ruby ajax ruby-on-rails-4


    【解决方案1】:

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

    如果你想单独保留它,那么你可以将 js 代码移动到部分并在index.html.erb 中呈现它。请参阅文档here

    更新

    如何使用部分:

    1. 创建_yourpartial.js.erb并填写js代码
    2. 要在 'index.html.erb' 中渲染代码,请添加:<%= render partial: 'yourpartial', formats: [:js] %>

    (当然你仍然需要在 js 代码周围加上 script 标签)

    【讨论】:

    • 你不喜欢js.erb局部的美丽吗? :)
    • 我的意思是创建_yourpartial.js.erb并在index.html.erb中渲染它
    • @ImranNaqvi,你检查过我更新的答案了吗?如果它看起来像文本,那么您只是忘记添加script 标签
    • 是的,你是对的,但我们不需要指定格式,只需指定 .js.erb 部分为render partial: 'yourpartial.js.erb'
    【解决方案2】:

    我会尽力帮助你。您可以将您的 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 请求。希望对您有所帮助。

    【讨论】:

    • 我想你没有注意到这个问题。我明确表示我希望 js.erb 没有 ajax 工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多