【发布时间】:2016-08-31 23:01:34
【问题描述】:
我无法在 ajax POST 请求中将参数传递给控制器操作。有我的代码:
$("#sendSubCatButton").click(function(){
var catId = $("#category_name").data("id");
var subCatName = $("#sous_category_name").val();
var lvlUrgenceMax = $("#sous_category_lvl_urgence_max option:selected").val();
// alert(catId);
// alert(subCatName);
// alert(lvlUrgenceMax);
$.ajax({
url: '/sous_categories',
type: 'POST',
dataType: 'json',
data: {
name: subCatName,
category_id: catId,
lvl_urgence_max: lvlUrgenceMax
}
});
});
还有我的控制器(仅相关部分):
def create
@create_new_subcategory = verifRight('create_new_subcategory')
if @create_new_subcategory
@category = Category.find(params[:category_id])
@sous_category = SousCategory.new(sous_category_params)
# Any category have a 'lvl_urgence_max', for those who create an incident.
# With that, we can determine how many an incident is important.
@sous_category.lvl_urgence_max.nil? ? @sous_category.lvl_urgence_max = 10 : false
respond_to do |format|
if @sous_category.save
format.json { render json: @sous_category.id, status: :created }
format.html { redirect_to edit_category_path(@category), notice: 'Vous venez de créer une sous catégorie.' }
else
format.json { render json: @sous_category.errors, status: :unprocessable_entity }
format.html { redirect_to :back, notice: 'Impossible de créer la sous catégorie.' }
end
end
else
renderUnauthorized
end
end
...
def sous_category_params
params.require(:sous_category).permit(:name, :category_id, :lvl_urgence_max)
end
在控制台中有:
在 2016 年 8 月 31 日 16:08:56 开始为 127.0.0.1 发布 POST "/sous_categories" +0200
由 SousCategoriesController#create as HTML 处理
参数:{"utf8"=>"✓", "authenticity_token"=>"EDqyXaq+2PekfJrLrmn/+16AnirzvySD+hkZj5+cQee2JD2ddMudDRJWXlZkCfKJ3mzw2AWuVAeCPr/y0Y1WVw==", "sous_category"=>{"name"=>"efsefesf", "lvl_urgence_max"=>"10}"} >
编辑:我评论了“警报”,但我可以在警报弹出窗口中看到 var“CatId”的值,但它没有通过。
【问题讨论】:
-
试试这个,从 ajax 代码中删除 datatype: json
-
Nope ...
{"utf8"=>"✓", "authenticity_token"=>"bQo4y190JEC//p1gf7RBdE0LOS1BvBQ9KnzntZ5lLO7LFLcLgQFhugnUWf211EwGzedX37etZLlSW0HI0HQ7Xg==", "sous_category"=>{"name"=>"efsefesfesf", "lvl_urgence_max"=>"10"}}我也尝试了 datatype: script 和 nope ...
标签: jquery ruby-on-rails ajax