[英]Is it possible to send a javascript variable to the create method of a controller?
我使用Rails 4。
我有一個用戶模型和一個記錄模型,我想將兩個JavaScript變量發送到控制器的create方法。
為此,我實現了一個AJAX調用:
var funds = $('input#test').val();
var weight = $('input#result').val();
$.ajax({
url: "/final",
type: "POST",
data: {
funds: funds,
weight: weight,
},
complete: function(){
console.log('Congrats');
}
});
我實現了將路由寫入我的配置路由文件中的路由:
post '/register' => 'users#create'
這是我的控制器:
def create @user = User.new(ticket_params) @funds = params([:funds]) @weight = params([:weight]) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } Record.create(fund: @funds, weight: @weight) else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end format.js end end
但是我收到一個錯誤400錯誤的請求。
我希望變量的funds
和weight
控制器的create方法中可用,以便我可以使用它們。
我讀到錯誤400錯誤請求表明我沒有為AJAX調用使用正確的動詞。 實際上,使用GET代替POST可以使錯誤消失。 但是當我創建用戶時,控制器說我的參數為空.....但是沒有! 我檢查了
如何將一些JavaScript變量發送到create方法?
這是來自瀏覽器網絡控制台的錯誤消息:
ActionController::ParameterMissing in UsersController#create
param is missing or the value is empty: user
Application Trace
app/controllers/users_controller.rb:109:in `user_params'
app/controllers/users_controller.rb:40:in `create'
我的控制台中的錯誤是:
POST http://localhost:3000/final 400 (Bad Request)
m.ajaxTransport.send @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
m.extend.ajax @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:6
(anonymous function) @ VM2175:27
m.event.dispatch @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5
m.event.add.r.handle @ jquery.self-ad66c584c2469d2bb527ba7aef5893549f1554ccc8ab3ccb43bd09ce8c3bf7a1.js?body=1:5
首先確認您具有:
Gemfile
中的Gemfile
gem 'jquery-rails'
//= require jquery
在您的application.js
//= require jquery
第二,您的data
具有,
應將其刪除:
$.ajax({
url: "/register",
type: "POST",
dataType: "json",
data: {
authenticity_token: $('meta[name=csrf-token]').attr('content'),
funds: funds,
weight: weight
},
complete: function(){
console.log('Congrats');
}
});
您可以在ajax data
參數中放置任意數量的參數。
讓我們知道您是否需要更多幫助
我終於找到了解決我問題的方法。
實際上,我正在使用User模型的_form.html.erb
文件。 我的意思是我正在處理的網頁是用戶正在填寫表單的網頁。 我想用AJAX調用做的是將一些參數發送到控制器的create方法,以便隨后可以在create方法中使用這些參數。
但是,在進行AJAX調用時,它會觸發其中包含所有代碼的方法的運行。 在我的控制器中,您可以看到第一行代碼檢索了ticket_params
,該ticket_params
應該是用戶在表單中填寫的信息。 但是這里是空的,因此用戶尚未單擊“提交”按鈕(他剛剛在形式輸入中觸發AJAX調用的過程中寫了一些東西)。
因此,我做的不是代替AJAX調用來將參數發送給create動作,而是為User模型聲明了另外兩個屬性,另外兩個使用了另外兩個hidden_field來保存每個javascript變量的 weight
和funds
並且當用戶單擊Submit時按鈕,我的參數自然會發送到create方法,在這里我可以使用代碼@user = User.new(ticket_params)
來檢索它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.