2014-05-10 115 views
0

我正在對Sinatra網站進行sms驗證功能。而我得到這個代碼: 將變量從Ruby傳遞到JavaScript

post '/coop/sendcode' do 
    @code = Random.rand(1000..9999).to_s 
    phone = params[:phone].to_s 
    HTTParty.get('http://sms.ru/sms/send?api_id=' + api_id + '&to=' + phone + '&text=' + @code) 
end 

這種觀點:

%form 
    %div.form-group 
    %label Phone 
    %input#phone.form-control{:name => "phone", :placeholder => "7 950 123 45 67"} 
    %button#sendsms.btn.btn-default{"data-toggle" => "modal", "data-target" => "#myModal"} Send 

而且這個JS:

$(document).ready(function(){ 
    $("#sendsms").click(function(){ 
     var phone = $("#phone").val(); 
     $.ajax({ 
     url: "/coop/sendcode", 
     data: {"phone": phone}, 
     type: "post" 
     }); 
    }); 
    $("#checkcode").click(function(){ 
     var serversCode = @code 
     var usersCode = $("#code").val(); 
     if (serversCode == usersCode) { 
     console.log("good: srv - " + serversCode + ", usr - " + usersCode); 
     } else { 
     console.log("bad: srv - " + serversCode + ", usr - " + usersCode); 
     } 
    }); 
    }); 

後用戶類型的電話號碼,他按上發送按鈕,打開模式窗口(帶按鈕#校驗碼)他可以從短信中輸入驗證碼。但是這段代碼不起作用,主要問題是如何通過@code變量從Ruby到JS?

預先感謝您。

回答