簡體   English   中英

如何在.js.coffee腳本導軌中使用路由

[英]How to use routes in .js.coffee script rails

我有以下代碼:

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

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

我猜這是兩個問題,或者正在尋找正確的方法。 如何使用shedule_details_create_path,如何在JavaScript中使用它? 還是有更好的方法來做到這一點?

感謝您的任何幫助。

如何毫不客氣地AJAXify表單,而不是訂閱“提交”按鈕的單擊處理程序:

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

這樣,您可以使用路由生成表單,並在標記中正確設置其action屬性。 那么您的javascript是完全獨立的。

js-routes gem非常適合我。

寶石文件:

gem "js-routes"

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

//= require js-routes

在第一次嘗試js-route之前,請刷新資產管道緩存,然后重新啟動Rails服務器:

rake tmp:cache:clear
rails s

最后在您的coffeescript文件中:

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即可

在您的routes.rb中,您可以編寫如下內容:

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

並將/ schedule_details / create放在ajax調用的url:param中。

希望我了解您的需求!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM