简体   繁体   English

Ruby on Rails路由前缀未在.erb.js文件中进行预处理

[英]Ruby on Rails routes prefixes not pre-processing in .erb.js file

I'm using Rails 4. I have the following file: 我正在使用Rails4。我有以下文件:

// apps/assets/javascripts/products.js.erb

var getColoursAndMaterialsData = function(onSuccess)
{
    var fd = formdata();

    $.post( '<%= data_products_path(:format => :json) %>', fd )
    .done(function(data)
    {
        onSuccess(data);
    });
};

When products.js.erb is included in a .html.erb file I get the error: 当products.js.erb包含在.html.erb文件中时,出现错误:

undefined method `data_products_path'

clearly routes prefix 'data_products_path' isn't being pre-processed. 显然,路由前缀“ data_products_path”没有经过预处理。 I was under the impression that giving the products.js the .erb extension would coax the pre-processor. 我给人的印象是给product.js提供.erb扩展名可以哄骗预处理器。

The same exact same code works when between the <script type="text/javascript"></script> tags in the .html.erb file. 在.html.erb文件中的<script type="text/javascript"></script>标记之间时,相同的代码完全相同。 The relevant part of my routes.rb looks like this: 我的routes.rb的相关部分如下所示:

resources :products do
    collection do     
        post 'data'
    end
end

Is there something else I need to do? 还有什么我需要做的吗?

I dont think it will work just by adding .erb extension. 我认为仅通过添加.erb扩展名就不会起作用。 why not do a simple jQuery ajax post request... 为什么不做一个简单的jQuery ajax发布请求...

use dataType: "json" to make sure you get json response and instead of using url helpers just specify the url. 使用dataType: "json"来确保获得json响应,而不是使用url helper而是指定url。

http://api.jquery.com/jquery.post/ http://api.jquery.com/jquery.post/

The link below answers your question 以下链接回答了您的问题

Using a Rails helper method within a javascript asset 在JavaScript资产中使用Rails辅助方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM