如何在JavaScript中访问Rails路由/ URL?

时间:2017-04-22 17:52:20

标签: javascript ruby-on-rails routing

我是Ruby on Rails的新手,所以请耐心等待。

所以,我刚刚为我的Web应用程序创建了以下URL:

HOMEPAGE (WHEN RUNNING PROJECT LOCALLY): localhost:3000
PRODUCTS PAGE: localhost:3000/products
TOYOTA PAGE: localhost:3000/products/toyota
HONDA PAGE: localhost:3000/products/honda
FORD PAGE: localhost:3000/products/ford
NISSAN PAGE: localhost:3000/products/nissan
CHEVROLET PAGE: localhost:3000/products/chevrolet
MERCEDES PAGE:  localhost:3000/products/mercedes
BMW PAGE: localhost:3000/products/bmw
HYUNDAI PAGE: localhost:3000/products/hyundai

这是我的config / routes.rb,我正在创建这些网址:

get 'products', to: 'static#products'
root to: 'static#home'

get 'products/toyota', to: 'static##products#toyota'
get 'products/honda', to: 'static#products#honda'
get 'products/ford', to: 'static#products#ford'
get 'products/nissan', to: 'static#products#nissan'
get 'products/chevrolet', to: 'static#products#chevrolet'
get 'products/mercedes', to: 'static#products#mercedes'
get 'products/bmw', to: 'static#products#bmw'
get 'products/hyundai', to: 'static#products#hyundai'

以下是我的产品页面的JavaScript文件片段:

    g.prototype.Ce = function(b,
        f) {

        var e = this;
        x.i.Mg(b, f);
        x.A("build/getModelOptions", {
            year: b,
            make: f,
            included_body_styles: x.options.included_body_styles
        }, function(b) {
            b = a.parseJSON(b);
            e.bg.render(b, function(b) {
                //$("#builder-make-selection .custom_dd_select a").text("Toyota");
                a("#builder_splash_models").html(b);
                a.each(a(".builder_body_types"), function(a, b) {
                    k(b);
                    console.log("b=" + JSON.stringify(b));
                    console.log("k(b)=" + JSON.stringify(k(b)));
                })
            })
        })
    };

基本上,我想要做的是,在JS中,在读取

的行中
       make: f;

如果我去丰田页面:我想把这一行写成:

      make: 'Toyota';

如果我去本田页面,我想要读一行:

      make: 'Honda'

如果我去福特页面,我想把这一行写成:

      make: 'Ford';

依此类推。你明白了。关于如何做到的任何想法?

1 个答案:

答案 0 :(得分:1)

我认为不应该考虑Rails来获取current url中的JavaScript。您可以轻松使用以下current url代码获取JavaScript

URL       -> document.location;
Path Name -> window.location.pathname;
Full URL  -> window.location.href;