将javascript变量传递给rails控制器

Cod*_*eky 9 javascript variables ruby-on-rails

这是我坚持的问题.我想将javascript变量传递给rails控制器.

<script>
var mdate = "26 December 2013";
var phone = prompt('Enter your phone!');
if (phone) {
    //Passing mdate and phone variables to rails controller(book_date & phone)
}
else
{
    alert("Cancelled");
}
</script>
Run Code Online (Sandbox Code Playgroud)

我的控制器

def new
        @booking = Booking.new
end
def create
    @booking = Booking.new(book_param)
    if @booking.save
        redirect_to root_url
    else
        flash[:notice_booking_failed] = true
        redirect_to root_url
    end
end

private
def book_param
    params.require(booking).permit(:id, :book_date, :phone)
end
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Siv*_*iva 9

从技术上讲,你不能在两种语言之间传递变量.

您可以通过在url中附加将这些值传递给rails控制器

<script>
var mdate = "26 December 2013";
var phone = prompt('Enter your phone!');
if (phone) {
    //Passing mdate and phone variables to rails controller(book_date & phone)
    window.open("localhost:3000//controller/create?mdate="+mdate+"&phone="+phone,"_self")
}
else
{
    alert("Cancelled");
}
</script>
Run Code Online (Sandbox Code Playgroud)

在你的控制器中

def create
    data = params[:date]
    phone = params[:phone]
    @booking = Booking.new(book_param)
    if @booking.save
        redirect_to root_url
    else
        flash[:notice_booking_failed] = true
        redirect_to root_url
    end
end
Run Code Online (Sandbox Code Playgroud)

注意:确保相应地配置config/route.rb

更多信息http://guides.rubyonrails.org/routing.html

  • 您可以轻松地通过隐藏字段传递数据. (3认同)

Rub*_*ist 6

jQuery中的Ajax代码:

$("#submit_button").submit(function(event) {

  /* stop form from submitting normally */
   event.preventDefault();

  /* get values from elements on the page: */
   var mdate = $('#mdate').val();
   var phone = $('#phone').val();

  /* Send the data using post and put the results in a div */
    $.ajax({
      url: "/BookCreate/?mdate="+mdate+"&phone="+phone,
      type: "post",
      data: values,
      success: function(){
        alert('Saved Successfully');
      },
      error:function(){
       alert('Error');
      }
    });
});
Run Code Online (Sandbox Code Playgroud)

路线:(因为我假设您的控制器名称是书)

match '/BookCreate', to: 'book#create'
Run Code Online (Sandbox Code Playgroud)

为此,您必须将jquery文件添加到您的代码或此链接

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述