问题描述
我正在 Sinatra 网站上实现注册的短信验证,我得到了这个代码:
I'm implementing sms-validation of registration on Sinatra site, and I got this code:
post '/reg' do
phone = params[:phone].to_s
code = Random.rand(1000..9999).to_s
HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + phone + '&text=' + code)
end
这从post请求中获取用户电话,然后生成4位代码,并通过get请求将代码发送到短信服务.但是,页面不会重新加载,因为此时会打开模态对话框,用户应该在其中键入 code.同时打开模态的按钮使用以下代码通过 Ajax 发送 post:
This take users phone from post request, than generates 4 digit code, and sends code on number via get request to sms service. But, page doesn't reloading, because at that moment opens modal dialog, where user should type code. Button which opens modal simultaneously sends post via Ajax with this code:
$(document).ready(function(){
$("#sendsms").click(function(){
var phone = $("#phone").val();
$.ajax({
url: "/coop",
data: {"phone": phone},
type: "post"
});
});
});
在客户端检查用户的代码会很奇怪,这就是我得到这个动作路线的原因:
It would be strange to check user's code on client side, thats why I got this action route:
post '/coop/checkcode' do
usrcode = params[:code]
if code == usrcode
redirect '/reg/success'
else
redirect '/reg/fail'
end
end
但我不能只是从 checkcode 路由中的第一条路由中获取并输入 code var.但我需要.
But I can't just take and type code var from first route in the checkcode route. But I need.
是否存在任何可能的方法来传递该变量或以其他方式实现它?
Is there exists any possible way to pass that variable or implement this somehow other way?
提前致谢.
推荐答案
您应该考虑使用会话:这里
首先在配置中:
enable :sessions
现在你得到:
post '/reg' do
phone = params[:phone].to_s
session[:code] = Random.rand(1000..9999).to_s
HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + phone + '&text=' + session[:code])
end
和
post '/coop/checkcode' do
usrcode = params[:code]
if session[:code] == usrcode
redirect '/reg/success'
else
redirect '/reg/fail'
end
end
这篇关于在 Sinatra 中的路由之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!