【发布时间】:2015-12-01 11:56:13
【问题描述】:
假设我有一个如下的简单表格
<%= form_for(@category) do |f| %>
<% if @category.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>
<ul>
<% @category.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :enabled %><br>
<%= f.check_box :enabled %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我想使用 ajax 请求提交此表单。我的表格 ID 是new_category。所以我尝试了这样的事情
<script type="text/javascript">
$("#new_category").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/categories',
dataType: "json",
success: function (result) {
return false
},
error: function () {
window.alert("Something went wrong! Please try again");
}
});
});
</script>
这不是提交我的表单。我想我错过了一些东西。另外,在提交表单之前,我想将名称字段内容替换为固定字符串“这是一个示例字符串”。并且需要发送一些其他的固定数据,比如"user_id" => current_user.id, "user_name" => current_user.name
user_id 和 user_name 这两个字段不在类别表中。那么我必须在控制器中将其列入白名单吗?如果是这样,那我该怎么做?
【问题讨论】:
-
不需要发送数据
data: $("#new_category").serialize()? -
是的,我需要发送表单的所有数据,但将名称字段内容替换为固定字符串并添加两个新数据
-
有一个 jquery $.ajax 选项
beforesend,你可以在那里做你的数据修改
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4