Jak wywołać metodę rails z jQuery
Mam ten kod JQuery:
$("p.exclamation, div#notification_box").live("mouseover", function() {
});
I chcę wywołać tę metodę rails z wnętrza kodu jQuery jako wywołanie zwrotne:
def render_read
self.user_notifications.where(:read => false).each do |n|
n.read = true
n.save
end
end
Ta metoda jest w moim modelu użytkownika. Jest na to jakiś sposób?
4 answers
Wykonaj wywołanie AJAX, skonfiguruj trasę, odpowiedz akcją kontrolera i wywołaj metodę.
# whatever.js
$("p.exclamation, div#notification_box").on("mouseover", function() {
$.ajax("/users/render_read")
});
# routes.rb
resources :users do
get :render_read, on: :collection
# or you may prefer to call this route on: :member
end
# users_controller.rb
def render_read
@current_user.render_read
# I made this part up, do whatever necessary to find the needed user here
end
PS: ten kod jest dla Rails 3.x i Ruby 1.9.x
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-16 19:51:35
Dobrze, że masz ten kod modelu. Musimy dodać nową akcję i upewnić się, że trasa jest ustawiona. Jeśli używasz zasobów, musisz dodać kolekcję lub członka. Ponieważ robisz aktualizację, wybrałbym PUT
jako metodę http.
Oto przykładowa trasa:
resources :user_notifications do
collection do
put 'render_read'
end
end
Dodaj akcję render_read
do kontrolera.
Twój kod jQuery będzie wyglądał mniej więcej tak:
$("p.exclamation, div#notification_box").live("mouseover", function() {
$.ajax({
url: "/user_notifications/render_read",
type: 'PUT'
});
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-09 06:37:26
Musisz skonfigurować kontroler po stronie serwera, aby wywołać metodę render_read
, a następnie możesz użyć $.ajax
lub $.post
w jQuery, aby złożyć wniosek.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-09 06:29:12
Normalnie JavaScript działa po stronie klienta, ale jest również możliwe, że aplikacja rysuje funkcję javaScript dla każdego klienta. W takim przypadku możesz użyć <%=
i tagów %>
W a .plik erb:
<script type="text/javascript">
$(function(){
new AClass.function({
text: <%= Date.today %>
});
});
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-29 22:31:30