Passing variables between routes in Sinatra

不问归期 提交于 2019-12-25 01:46:28

问题


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

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

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?

Thank you in advance.


回答1:


You should look into using sessions: here

first in config:

enable :sessions

now you get:

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

and

post '/coop/checkcode' do
  usrcode = params[:code]
  if session[:code] == usrcode
    redirect '/reg/success'
  else
    redirect '/reg/fail'
  end
end


来源:https://stackoverflow.com/questions/23621511/passing-variables-between-routes-in-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!