我正在辛纳特拉练习制作一个web应用程序,我正在尝试更新一个页面,这样一旦点击按钮,数据库中的信息就会显示出来(更确切地说,我是一个使用学生年龄、姓名和校园位置的学生数据库)。我有一个有5个按钮的路径(每个校园一个),一旦点击了一个校园按钮,我希望页面与所有来自该校园的学生信息更新在同一个页面上。
这就是我为app.rb准备的
require 'sinatra'
require 'sqlite3'
set :public_folder, File.dirname(__FILE__) + '/static'
db = SQLite3::Database.new("students.db")
db.results_as_hash = true
get '/' do
@students = db.execute("SELECT * FROM students")
erb :home
end
get '/students/new' do
erb :new_student
end
get '/students/campus' do
erb :campus
end
get '/students/campus/:campus' do
erb :campus
campus_data = db.execute("SELECT * FROM students WHERE campus=?", params[:campus])
campus_data.to_s
response = ""
campus_data.each do |student|
response << "ID: #{student['id']}<br>"
response << "Name: #{student['name']}<br>"
response << "Age: #{student['age']}<br>"
response << "Campus: #{student['campus']}<br><br>"
end
response
end
post '/students' do
db.execute("INSERT INTO students (name, campus, age) VALUES (?,?,?)", [params['name'], params['campus'], params['age'].to_i])
redirect '/'
end这就是我为campus.erb准备的
<!DOCTYPE html>
<html>
<head>
<title>Campus Cohorts</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Cohorts</h1>
<p>Click on a button to see all students from that location.</p>
<a href="/students/campus/SF"><button type="button">San Francisco</button></a>
<a href="/students/campus/NYC"><button type="button">New York City</button></a>
<a href="/students/campus/SD"><button type="button">San Diego</button></a>
<a href="/students/campus/CHI"><button type="button">Chicago</button></a>
<a href="/students/campus/SEA"><button type="button">Seattle</button></a>
</body>
</html>现在,如果点击一个按钮,它会将你重定向到一个新的页面,与学生的信息形式的校园,我如何能够在同一页上呈现的信息?
发布于 2017-04-14 20:34:42
听起来好像您想要执行AJAX调用。您必须编写一些javascript才能从服务器获取学生视图并将其插入当前页面。
使用javascript库,如jQuery:http://api.jquery.com/jquery.ajax/
这样做的目的是在校园按钮上绑定一个click事件,并对校园按钮的href提供的URL进行AJAX调用。服务器将响应该校园的呈现视图,并将其返回给您的javascript函数。然后您可以将它插入到页面中。
例如:
将类添加到按钮中(为了使用jQuery轻松地选择它们):
<a class="campus" href="/students/campus/SF"><button type="button">San Francisco</button></a>现在您可以编写javascript了。您必须创建一个javascript文件,并将其包含到您的应用程序布局中。Sinatra提供来自应用程序的./public目录的静态资产,如css和javascript文件。然后,在应用程序布局html文件的底部编写<script src="you_file.js"></script>。您还必须使用下载jQuery文件并执行同样的操作,只需确保jQuery文件包含在您自己的javascript文件之上的应用程序布局中,即
<script src="the-downloaded-jquery-file.js">
<script src="you-file.js">在这个javascript文件中,您可以定义您的jQuery函数来实现AJAX调用。
单击处理程序和AJAX调用:
# When the document receives a click on a '.campus' element run this function
$(document).on('click', '.campus', function(){
var path = this.href; # grab the route
# jQuery provides this convenient AJAX method that will fetch the HTML
# returned by calling the server at the path URL and insert it into 'body'
$('body').load(path)
});事情就是这样。jQuery load函数将向单击的校园链接的路径发送AJAX请求。服务器将在get '/students/campus/:campus' do路由上接收请求,并使用呈现的结果进行响应。然后,jQuery将用结果替换body标记的内容。
免责声明:您可能必须将此示例与您的用例相匹配,但这将为您指明正确的方向。本答覆所涉及的一些课题包括:
编码愉快!
https://stackoverflow.com/questions/43418583
复制相似问题