0
我一直在試圖弄清楚我在做什麼錯誤 - 我試圖發送一個Ajax請求與一些數據,然後打開一個模態表單:無法在Rails中通過Ajax請求傳遞參數
var position = $(".exercise-list").sortable('toArray');
var positionData = "["+position+"]"
$.ajax({
url: window.location.href + '/create_workout_routine',
method: 'POST',
data: {
position: positionData
},
success: (function() {
return false
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
return false
})
});
$('#createWorkoutModal').modal('show');
當我嘗試console.log(positionData);我得到
[4,2]
這正是我所需要的。同樣的,我的日誌:
Started POST "/workouts/new/create_workout_routine" for 127.0.0.1 at 2014-12-10 18:52:11 -0600
Processing by WorkoutsController#new as */*
Parameters: {"position"=>"[4,2]"}
這裏是我的控制器:
def create
exercise_order = params[:position]
@workout = Workout.new(workout_params)
WorkoutRoutine.create(
exercise_order.each_with_index.map { |x,i|
{:exercise_id => x,
....
}
}
)
...
end
當我createWorkoutModal彈出時,我提交表單,並得到這個錯誤:
NoMethodError (undefined method `each_with_index' for nil:NilClass):
app/controllers/workouts_controller.rb:29:in `create'
我也試過,包括在ajax請求的成功函數中發生的模式彈出窗口以及沒有運氣,以及擺脫「返回false」部分。我很困惑,爲什麼當我看到傳遞的參數時它給了我'無',任何幫助都非常感謝!
我仍然得到同樣的錯誤 – asalgan 2014-12-11 14:38:19