【发布时间】:2018-06-21 06:02:59
【问题描述】:
在我的 Sinatra 视图中,我有一个表格,它将显示我数据库中的所有记录。当我单击删除记录时,我将调用 jquery ajax 来发送删除请求。然后我的路由将处理请求,删除数据库中的记录并将应用程序重定向到其主页。
问题是视图在删除后没有刷新并且仍然显示一些旧数据。当我关闭浏览器并再次打开时,即使删除请求返回了 200 代码状态,数据仍然存在于视图中。
# application_controller.rb
require 'sinatra'
require 'sinatra/reloader'
require './application_helper' if development?
enable :logging
helpers ApplicationHelper
...
delete '/delete/:record_id' do
id = get_record_id
delete_record id
redirect '/'
end
get '/' do
@links = get_all @user_ip
erb :index, { :layout => :layout }
end
这是视图的简化代码:
# index.erb
<% if !@links.empty? %>
<div class="table-responsive" style="margin-top: 30px">
<table class="table table-striped table-hover" style="width: 600px">
<thead>
<tr>
<th>Original URL</th>
<th>Short URL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<% @links.each do |record| %>
<tr>
<td><a href=<%= record.long_url %>><%= record.long_url %></td>
<td><a href=<%= record.id %>><%= record.short_url %></td>
<td>
<button class="btn btn-default" onClick="deleteRecord(<%= record.id %>)">
<span class="glyphicon glyphicon-trash" style="color: red"></span>
</button>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% end %>
这里是 GitHub 上的完整源代码:https://github.com/huyvohcmc/bitly
【问题讨论】:
-
sinatra 在您进行 ajax 调用时不会重新加载视图。如有必要,您将不得不使用 javascript 重写 dom。您可以通过 json 返回数据,然后使用该数据刷新表格。
标签: jquery ruby ajax sinatra rack