【问题标题】:How do I post a variable via ajax to a ruby script?如何通过 ajax 将变量发布到 ruby​​ 脚本?
【发布时间】:2016-07-14 21:51:00
【问题描述】:

我敢肯定,这应该很简单,但我是一个超级新手。基本上,有一个带有电话号码表单字段的网站,当用户点击提交时,它将向电话号码发送一条消息。 (使用 Twilio)

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} );

红宝石('_/ruby/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

当我在终端中执行 ruby​​ 文件时,它可以使用静态 ':to' 变量。但我不能让他们一起工作。你能告诉我我做错了什么吗?我敢肯定有很多东西......仅供参考,这就是我们使用的所有红宝石。没有其他红宝石文件。 php 给我们带来了问题。

【问题讨论】:

    标签: javascript ruby ajax http-post twilio


    【解决方案1】:

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

    # 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
    

    【讨论】:

    • 嗨。谢谢!我一定会尝试的。当您说关联路线时,您的意思是我要建立一个完整的rails项目吗?或者只是创建一个 routes.rb 帖子 '_/ruby/messages_controller.rb',到:'messages_controller#create' ?
    • 您将需要某种 Web 框架来接收来自 AJAX 的请求。你可以使用 Rails 或者更小的东西,比如 Sinatra。您需要研究这些框架并了解您的想法。
    猜你喜欢
    • 2017-03-14
    • 2014-09-18
    • 2015-09-13
    • 2013-09-29
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    相关资源
    最近更新 更多