简体   繁体   English

无法在Rails中通过Ajax请求传递参数

[英]Unable to pass params via Ajax request in Rails

I've been racking my brain trying to figure out what I'm doing wrong here - I'm trying to send an ajax request with some data and then open up a modal form: 我一直在绞尽脑汁试图找出我在这里做错了什么-我正在尝试发送带有一些数据的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');

When I try console.log(positionData); 当我尝试console.log(positionData); I get 我懂了

[4,2] [4,2]

which is exactly what I need. 这正是我所需要的。 Same with my logs: 与我的日志相同:

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]"}

Here's my controller: 这是我的控制器:

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

When my createWorkoutModal pops up, I submit the form, and get this error: 当我的createWorkoutModal弹出时,我提交表单,并得到以下错误:

NoMethodError (undefined method `each_with_index' for nil:NilClass):
  app/controllers/workouts_controller.rb:29:in `create'

I also tried including the modal popup to occur in the success functon of the ajax request as well with no luck, as well as getting rid of the "return false" part. 我还尝试过将模式弹出窗口包含在ajax请求的成功函数中,并且没有运气,还尝试了“返回假”部分。 I'm confused as to why it's giving me 'nil' when I can see the params being passed, any help is much appreciated! 当我看到参数已通过时,为什么它为什么给我“零”,我感到困惑,任何帮助都将不胜感激!

replace the following line in your controller 替换控制器中的以下行

exercise_order = params[:position]

with this 有了这个

exercise_order = params["position"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM