gpt4 book ai didi

javascript - 将 javascript 变量传递给 Rails Controller

转载 作者:可可西里 更新时间:2023-11-01 02:58:06 25 4
gpt4 key购买 nike

这是我遇到的问题。我想将 javascript 变量传递给 Rails Controller 。

<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>

我的 Controller

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 Controller

<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>

在你的 Controller 中

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

关于javascript - 将 javascript 变量传递给 Rails Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com