【发布时间】:2016-11-22 11:34:30
【问题描述】:
我在使用 Ajax on Rails 时遇到了错误的请求错误 400。 当我提交表单时,我有一个字符串作为参数从 Jquery 发送,我想从 params[:assignee] 中检索它,以便我可以提取字符串并通过我的控制器保存它。 我的控制器:
def create
@task = Task.new(task_params)
@task.user = current_user
username = params.permit[:assignee]
@task.assignee = username
#set_category
respond_to do |format|
if @task.save
format.html { redirect_to tasks_url, notice: 'Task was successfully created. '+task_params.inspect}
#format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: @task }
else
format.html { render :new }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
def task_params
params.require(:task).permit(:owner, :value, :completed, :category, :date, :assignee)
end
这是我的 JS:
$( "#new_task" ).submit(function() {
alert("form: "+assignee);
//event.preventDefault();
$.ajax({
url: "/tasks",
type: "POST",
data: {assignee},
dataType: "json",
success: function(data) {
alert('successfully');
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText+""+textStatus+""+error);
}
});
});
assignee 是在 jquery 自动完成表单中选择的用户名:
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
assignee=this.value;
$('input[name=commit]').prop("disabled",false);
return false;
}
我的根目录是“task/”,您可以在其中查看已保存的任务和创建新任务的表单。 我在网上搜索了很多,我都试过了。我能怎么做?非常感谢
【问题讨论】:
-
你在浏览器控制台中得到了什么?
-
404错误意味着客户端找不到路由。检查你的 routes.rb。
-
对不起,我的错!是 400。控制台:localhost:3000/tasks400(错误请求)
-
@AlexBeginner
assignee变量里面是什么?您能否将该变量的输出添加到问题正文中? -
受让人是一个字符串
标签: javascript jquery ruby-on-rails ajax bad-request