将javascript变量传递给rails控制器

时间:2013-12-26 14:56:20

标签: javascript ruby-on-rails variables

这是我坚持的问题。我想将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>

我的控制器

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

提前谢谢!

3 个答案:

答案 0 :(得分:7)

从技术上讲,你无法在两种语言之间传递变量。

您可以通过附加到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>

在您的控制器中

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

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

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

答案 1 :(得分:5)

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

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

match '/BookCreate', to: 'book#create'

为此,您必须将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>

enter image description here

答案 2 :(得分:0)

您可以使用类似

的内容
$.post("/bookings?booking[phone]=" + phone + "&booking[book_date]=" + mdate)

将使用params hash进行BookingsController#create操作:

{ booking: { phone: "entered from prompt", book_date: "26 December 2013" } }