【问题标题】:How to use routes in .js.coffee script rails如何在 .js.coffee 脚本中使用路由
【发布时间】:2011-10-04 17:45:20
【问题描述】:

我有这个代码:

$('#my_form .submit').click( ->
  $.ajax( ->
  type: "post",
  url: "????",
  data: $("#myform").serialize(),
  #success: this.saveUserResponse
)

POST   /schedule_details(.:format)                   {:action=>"create", :controller=>"schedule_details"}

我猜这是 2 个问题,或者正在寻找正确的方法。如何使用 shedule_details_create_path 以及如何在我的 javascript 中使用它?或者,有没有更好的方法来做到这一点?

感谢您的帮助。

【问题讨论】:

    标签: javascript routes ruby-on-rails-3.1 coffeescript


    【解决方案1】:

    如何不显眼地 AJAXify 表单而不是订阅提交按钮的点击处理程序:

    $('#my_form').submit(function() {
        $.ajax({
            type: this.method,
            url: this.action,
            data: $(this).serialize(),
            success: this.saveUserResponse
        });
        return false;
    });
    

    通过这种方式,您可以使用路由生成表单,并在标记中正确设置其操作属性。那么你的javascript就完全独立了。

    【讨论】:

    • 太棒了,我知道我只是想多了。谢谢!
    【解决方案2】:

    js-routes gem 非常适合我。

    宝石文件:

    gem "js-routes"
    

    在 application.js 中需要 js 路由文件。

    //= require js-routes
    

    在第一次尝试 js-routes 之前刷新资产管道缓存并重新启动您的 Rails 服务器:

    rake tmp:cache:clear
    rails s
    

    最后在您的咖啡脚本文件中:

    Routes.users_path()
    # => "/users"
    Routes.user_path 1
    # => "/users/1"
    Routes.user_path 1, format: 'json'
    # => "/users/1.json"
    Routes.user_path 1, anchor: 'profile'
    # => "/users/1#profile"
    Routes.new_user_project_path 1, format: 'json'
    # => "/users/1/projects/new.json"
    

    如需高级配置,请查看js-routes github repo。

    【讨论】:

    • @dbugger 好的,我会在我的答案中添加更多细节。
    【解决方案3】:

    在你的 routes.rb 中你可以这样写:

    match "/schedule_details/create" => "schedule_details#create"
    

    并把 /schedule_details/create 放在你的 ajax 调用的 url: 参数中。

    希望我理解您的需求!

    【讨论】:

    • 将 /schedule_details/create 放在 url 参数中的问题是我的测试机器使用 localhost:3000/schedule_details/create,但我的生产机器是 example.com/ts/schedule_details/create。所以 /schedule_details/create 会在生产机器上中断。谢谢你的信息
    猜你喜欢
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2015-08-05
    • 2012-11-18
    • 2013-03-01
    • 1970-01-01
    • 2012-04-06
    • 2021-01-16
    相关资源
    最近更新 更多