将javascript变量传递给rails控制器

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

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

我的控制器

 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 

先感谢您!

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

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

  

在你的控制器中

 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

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文件添加到您的代码或此链接

   

在此处输入图像描述

你可以使用类似的东西

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

它将使用params hash转到BookingsController#create action:

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