以下代碼旨在與sinatra一起使用,以從ERB生成的HTML頁面獲取值。它調用一個斐波那契序列生成器並將輸入值從HTML發送到生成器。然後該代碼返回一個句子,其中包含用戶輸入生成的斐波那契數列中的後10位數字。然後我希望它能夠將該返回值傳遞給HTML ERB頁面。我已經在這裏和其他網站上嘗試了許多解決方案,但還沒有找到解決我的問題的解決方案。返回值爲erb值
主代碼: 文件名:* /項目/ webhosted_custom_fibonacci_calculator.rb
require "rubygems"
require "sinatra"
require_relative 'fibonacci_calculator.rb'
require "erb"
include Calculator
get '/' do
redirect ("/calculate")
end
get '/calculate' do
erb :calculator_form, :locals => {:calculator => session[:calculator]}
end
post '/calculate' do
num1 = params['firstnum'].to_i
num2 = params['secondnum'].to_i
output = Calculator.run(num1, num2)
redirect ("/results_form?results=#{output}")
end
get '/results_form' do
erb :results_form, :locals => {:results => params[:results]}
end
計算器: 文件名:* /項目/ fibonacci_calculator.rb
module Calculator
def run(arg1, arg2)
number = [2]
number[0] = arg1 # Takes in passed values
number[1] = arg2
first_number = number[0].to_i # Makes sure inputs are integer values
second_number = number[1].to_i
storage = []
calculate_next = 0
usage_number_1 = 0
usage_number_2 = 1
storage[0] = first_number
storage[1] = second_number
for i in (0..8)
usage_number_1 = storage[i].to_i
usage_number_2 = storage[i+1].to_i
calculate_next = usage_number_1 + usage_number_2
storage.push(calculate_next)
end
return "The values are: #{storage}" # Return value works fine
end
end
輸入表格: 文件名稱:*/projects/views /calculator_form.erb
<html>
<head>
<title>Fibonacci Calculator</title>
</head>
<body>
<h1>Welcome to the Custom Fibonacci Sequence Calculator</h1>
<form action="/calculate" method="POST">
First Number: <input type="number" name="firstnum" id = "1stnum" ><br>
Second Number: <input type="number" name="secondnum" id = "2ndnum"><br><br>
<input type="submit" value="Submit"><br>
</form>
</body>
</html>
結果形式: 文件名:* /項目/視圖/ results_form.erb
<html>
<head>
<title>Fibonacci Calculator</title>
</head>
<body>
<h1>Results</h1>
<form action="/result" method="POST">
<input type="text" name = "results" id = "out" size = "200" maxlength="600">
</form>
</body>
</html>
注:我得到的返回值,可以調出結果表單,但返回值不通過。