javascript - 尝试使用ajax更新rails索引中的复选框值
问题描述
在 Rails 应用程序中单击时,需要此 ajax 代码的一些帮助来更改复选框中 index.html.erb 中的布尔列。我是 javascript 新手。
<% @budget_histories.each do |budget_history| %>
<tr>
<li class="checkbox m-b-15">
<label>
<input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
<i class="input-helper"></i>
</label>
</li>
</tr>
<% end %>
function checkAllBudgetHistoryItems(el, id) {
if (el.checked) {
$.ajax({
type: 'PUT',
url: '/budget_histories/update',
data: 'budget_history_item_' + id,
success: function (data) {
$("#budget_history_items_tbody input").prop('checked', false);
}
});
} else {
$.ajax({
type: 'PUT',
url: '/budget_histories/update',
data: 'budget_history_item_' + id,
success: function (data) {
$("#budget_history_items_tbody input").prop('checked', true);
}
});
}
}
单击复选框时,如何使用 ajax 从我的数据库中更新 accept(boolean) 属性?
解决方案
我已经解决了这样的问题:
- 创建控制器方法:
def accept_budget
if @budget_history.toggle!(:accept)
render json: {}, status: :ok
else
render json: @budget_history.errors, status: :unprocessable_entity
end
end
- 创建路线
resources :budget_histories do
member do
put :accept_budget
end
end
- 复选框 html
<li class="checkbox m-b-15">
<label>
<input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
<i class="input-helper"></i>
</label>
</li>
- 编辑脚本:
<script language="javascript">
function checkAllBudgetHistoryItems(el, id) {
if (el.checked) {
$.ajax({
type: 'PUT',
url: '/budget_histories/' + id + '/accept_budget',
data: 'budget_history_item_' + id,
success: function (data) {
$(el).prop('checked', true);
}
});
} else {
$.ajax({
type: 'PUT',
url: '/budget_histories/' + id + '/accept_budget',
data: 'budget_history_item_' + id,
success: function (data) {
$(el).prop('checked', false);
}
});
}
}
</script>
推荐阅读
- kubernetes - Kubernetes 节点中的高内核内存使用率
- xamarin - xamarin 表单自定义呈现的选择器
- javascript - 如何使用 Javascript 验证表单并且在提交后不重新加载页面?
- c - 使用 C 绕过声音/音频文件 (WAV)
- terraform - 如何修复预期的类型“字符串”,得到不可转换的类型“[]interface {}”?
- javascript - 节点快速路由传递变量到所需模块
- c# - 将 JSON 与父名称 C# 结合
- sql - 知道如何从今天的日期检索属于前一周的日期吗?
- json - postgres:查找与数组中的值匹配的嵌套json值
- sql-server - T-SQL 高效使用 PARTITION BY 和 DISTINCT