[英]Using link_to to only call a function in rails when the link is clicked
我是Rails的新手。 我試圖僅在單擊鏈接時才調用函數check(),但是控制器每次加載視圖時也會調用該函數。
路線: routes.rb
Rails.application.routes.draw do
get 'welcome/index'
resources :articles
控制器: articles_controller.rb
class ArticlesController < ApplicationController
helper_method :check
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def check
puts "check"
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
private
def article_params
params.require(:article).permit(:title, :text)
end
型號: article.rb
class Article < ActiveRecord::Base
end
查看: index.html.erb
<h1>
<%= link_to 'Call on click', :onclick => check() %>
</h1>
如果您想從link_to
撥打一些路線來嘗試
link_to "Call on click", controller: "articles", action: "check"
然后只需添加一條路線即可get 'articles/check'
在您的click函數中添加以下語句,以防止調用控制器的操作
function click(event){
event.preventDefault();
your previous app logic
}
在您的routes.rb
添加以下內容:
get '/articles/check' => 'articles#check', as: :check_article
然后在您看來,您應該執行以下操作:
<%= link_to "Check article", check_article_path, remote: true %>
注意remote:
選項,它將告訴Rails通過ajax發送請求,而不是加載新頁面(Im假定這是預期的行為)。
現在,由於您是通過ajax發送請求的,所以Rails應該使用一些JavaScript來響應請求。 在CoffeeScript中將是這樣的:
#views/articles/check.js.coffee
$ ->
$("a[data-remote]").on "ajax:success", (e, data, status, xhr) ->
alert "Article was checked."
您在sever-side
(Rails)事件和client-side
(JS)事件之間感到困惑。
考慮以下:
#config/routes.rb
resources :articles do
get :check, on: :collection #-> url.com/articles/check
end
#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def check
# do something
end
end
以上將允許您使用...
<%= link_to "Check", articles_check_path %>
每次“單擊”鏈接時都會觸發,確實會導致瀏覽器將您帶到您要查看的新操作/視圖。
以上是服務器端功能。 這是標准的HTTP
。
您將上述內容與javascript混淆了:
#app/assets/javascripts/application.js
var check = function() {
// do something
}
以上內容僅在客戶端使用 ,只能使用javascript中的onclick
/ .on("click"
事件處理程序進行調用:
<%= link_to "Check", some_path, onclick: "return check();" %>
這是客戶端,僅適用於加載到DOM
元素。 它通常用於為應用程序的前端提供額外的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.