2016-07-14 33 views
0

这应该是非常简单,我敢肯定,但我是一个超级新手。基本上,有一个网站带有一个电话号码的表单字段,当用户点击提交时,该电话号码将向该电话号码发送消息。 (使用Twilio)如何通过ajax将变量发布到ruby脚本?

的javascript:

$("#phoneNumberButton").click(function(){ 
console.log($("#styled").val()); 

var phoneNumberString = $("#styled").val(); 
phoneNumberString = phoneNumberString.replace(/\D/g,''); 
if (phoneNumberString.length != 10) { 
    $('#styled').tooltipster('show'); 
} else { 
$('#phoneNumberButton').text('Link sent!'); 
$.post('_/ruby/TwilioSend.rb', {'phoneNumber': phoneNumberString}); 

红宝石('_ /红宝石/ TwilioSend.rb):

require 'twilio-ruby' 

account_sid = "xxxx" 
auth_token = "yyyy" 

@client = Twilio::REST::Client.new account_sid, auth_token 
message = @client.account.messages.create(:body => "Hello from Ruby", 
:to => params[:phoneNumber], # Replace with your phone number 
:from => "+15555555555") # Replace with your Twilio number 

puts message.sid 

红宝石文件工作,当我在终端执行它,使用静态':到'变量。但我无法让他们一起工作。你能告诉我我做错了什么吗?我相信有很多东西...... fyi,这就是我们使用的所有红宝石。没有其他的ruby文件。 PHP导致我们的问题。

回答

0

使调用Twilio的代码需要在Rails控制器中。控制器将有一个关联的路线,例如:

# controllers/messages_controller.rb 
class MessagesController < ApplicationController 
    def create 
    client = Twilio::REST::Client.new(account_sid, auth_token) 
    message = client.account.messages.create(:body => "Hello from Ruby", :to => params[:phoneNumber], :from => "+15555555555") 

    render :json => { :sid => message.sid } 
    end 
end 

# config/routes.rb 
... 
resources :messages 
+0

嗨。谢谢!我一定会尝试。当你说关联的路线时,你的意思是我要建立一个整体的铁路项目?或者只是创建一个routes.rb文章'_/ruby​​/messages_controller.rb',以:'messages_controller#create'? –

+0

您将需要某种Web框架才能接收来自AJAX的请求。你可以使用Rails或更小的东西,比如Sinatra。您需要查看这些框架并了解您的想法。 – philnash

相关问题