【发布时间】:2013-07-20 01:25:02
【问题描述】:
我正在尝试向我的 rails 控制器发送 AJAX 请求(items controller 中的 make_suggestion 方法)。
我有以下 javascript:
$.ajax({
url: "/items/make_suggestion", // pass to make_suggestions in recipes controller
type: "POST",
dataType: 'json',
data: parsed_data // a Javascript object/data hash
});
启用 debug(params) 后,我在 params 中看不到任何 parsed_data。
谁能指出什么是错的?以及如何通过触发 AJAX 在 Rails 的参数中创建符号?
更新
在我的控制器中,我有
def make_suggestion
respond_to do |format|
format.html
format.json { render :json => params }
end
end
我的 ajax 代码:
$.ajax({
url: "http://localhost:3000/items/make_suggestion", // I'm doing the proper routing later, since '/make_suggestion' routes to 'items/1/make_suggestion'
type: "POST",
dataType: 'json',
data: parsed_data,
success: function(returned_value){
if(returned_value)
alert('true');
$('.test').append(returned_value);
},
error: function(returned_value){
$('.test').html('<p>Error in AJAX request</p>');
alert('Not working');
}
});
我的 parsed_data 看起来像这样:
参数:{"data1"=>{"position"=>"1", "item_id"=>"item_1", "to_do"=>"未知", "selected"=>"false"}, "data2"=>{"position"=>"2", “item_id”=>“item_2”,“to_do” =>“未知”,“选定”=>“假”},“data3”=>{“位置”=>“3”,“item_id”=>“item_3”,“to_do”=>“未知”,“选中"=>"假"}, "data4"=>{"position"=>"4", "item_id"=>"item_4", "to_do"=>"unknown", "选中"=>"false"}, "data5"=>{"position"=>"5" , "item_id"=>"item_5", "to_do"=>"unknown", "selected"=>"false"}}
但是当我转到 /items/make_suggestion.json 时,它只显示以下内容:
{"action":"make_suggestion","controller":"recipes","format":"json"}
【问题讨论】:
-
我的猜测是你的
parsed_data变量为空 - 尝试将其输出到浏览器 javascript 控制台 -
看来你准备好了?我假设上面的
Parameters输出来自您的rails 日志?所以只需根据需要访问 Rails 操作中的任何参数数据params[:data1][:item_id] # => item_1 -
parsed_data 一直存在,但问题是我无法访问 params 数据。 params 哈希不包含任何 parsed_data (请参阅问题的最后一行)
-
不确定您说“但是当我访问 /items/make_suggestion.json ...”时的意思是指您在浏览器地址栏中输入了“localhost:3000/items/make_suggestion.json”吗?跨度>
-
是的,我就是这个意思
标签: javascript jquery ruby-on-rails