【发布时间】:2017-07-19 17:50:39
【问题描述】:
好的,我正在寻找一种让 ajax 脚本在页面后台运行并查看数据库中是否有新记录以及是否有抓取该记录并将其显示在我的页面。
我也不想使用插件,我宁愿自己做,因为我更喜欢学习如何做,如果我将来需要它来做不同的事情,更容易做出改变
我对 ajax 和 ruby on rails 还很陌生,所以需要解释一下
这是我的控制器,当我用户更新它更改的内容而不刷新页面但我想要它也获取新数据时
class NotificationsController < ApplicationController
# GET /notifications
# GET /notifications.json
def index
@notifications = Notification.all
end
def show
end
def update
@notification = Notification.find(params[:id])
@notification.update_attributes(:content => params[:content][:content])
respond_to do |format|
format.html { redirect_to notifications_path }
format.json { render json: @notification}
end
end
end
这是js文件
$(document).ready(function(){
$('input[type=submit]').on('click', function(event){
var form = $(this).parent('form');
event.preventDefault();
$.ajax({
type:"POST",
url: form.attr('action'),
data: form.serialize(),
success: function(data){
console.log('this worked')
$('#'+ data.id).html(data.content)
},
error: function(data){
console.log('failed')
},
dataType: 'JSON'
});
});
});
这是我的html文件
<% content_for :titleheader do %>
NOTIFICATIONS
<% end %>
<h1>Listing Notifications</h1>
<% @notifications.each do |notification| %>
<%= form_for notification do |f| %>
<%= notification.id %>
<div id="<%= notification.id %>"><%=notification.content %></div>
<%= notification.read %>
<%= text_field "content", "content" %>
<%= f.submit "change status" %>
<% end %>
<% end %>
如您所知,我还没有进行创建操作,因为我不确定是否必须通过 ajax 或其他方式来执行此操作
非常感谢您的帮助
【问题讨论】:
-
这是一个不好的问题还是没有人知道答案?
标签: javascript jquery ruby-on-rails ajax live