当前位置: 动力学知识库 > 问答 > 编程问答 >

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

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); I get

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

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. 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"]
分享给朋友:
您可能感兴趣的文章:
随机阅读: