![](/img/trans.png)
[英]ajax post form when checkbox is changed jquery ajax not working
[英]RoR Ajax and jQuery Post Form from Checkbox
RoR的新手,請原諒。
在4.0.0.rc1上運行,我將Devise用於LDAP身份驗證
我正在嘗試制作“任務列表”應用程序,並且在使用AJAX和jQuery調用的索引視圖中遇到了一些麻煩。 我試圖讓一個foreach循環遍歷任務列表中的元素,每個元素都以單獨的形式列出。 任務列表將根據當前日期自動提供。 為了開發目的,我有一個text_field元素代替了自動生成的任務列表。
當用戶單擊復選框時,我想為表單提供POST SUBMIT,同時重定向回初始索引。 提交后,還應具有已登錄用戶的用戶ID以及隨POST一起提供的日期。 即:
[TaskName] [UserID(空白)] [Date(空白)]完成了嗎? [復選框]
[TaskName] [UserID] [Date]完成了嗎? [復選框(禁用)]
我目前擁有以下代碼,在過去的幾天里,我一直在研究這些代碼,但仍在努力工作。
app / views / weeks / index.html.erb:
<table>
<thead>
<tr>
<th>Task</th>
<th>Completed by</th>
<th>Completed on</th>
<th>Completed</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<%= form_for(Week.new, remote: true) do |f| %>
<td><%= f.text_field :task %></td>
<td><%= f.hidden_field :completed_by, :value => current_user.login %></td>
<td><%= f.hidden_field :completed_on, :value => DateTime.current().in_time_zone('EST').to_formatted_s(:short) %></td>
<td><%= f.check_box :completed, :onchange => '$(this.form).submit();' %></td>
<% end %>
</tr>
</tbody>
</table>
app / views / assets / javascripts / weeks.js.coffee:
$(document).ready ->
$("#new_week").on("ajax:success", (e,data,status,xhr) ->
$("#new_week").append xhr.responseText
).on "ajax:error", (e, xhr, status, error) ->
$("#new_week").append "<p>ERROR</p>"
app / controllers / weeks_controller.rb:
class WeeksController < ApplicationController
before_action :set_week, only: [:show, :edit, :update, :destroy]
# POST /weeks
# POST /weeks.json
def create
@week = Week.new(week_params)
respond_to do |format|
if @week.save
format.html { redirect_to @week, notice: 'Week was successfully created.' }
format.json { render action: 'show', status: :created, location: @week }
else
format.html { render action: 'new' }
format.json { render json: @week.errors, status: :unprocessable_entity }
end
end
end
嗯,我注意到的一件事是您示例中的weeks#create操作無法處理js請求。
如何在我的應用程序中實現簡單的遠程表單和js模板。
# POST /weeks
# POST /weeks.json
def create
@week = Week.new(week_params)
respond_to do |format|
if @week.save
format.js
else
format.js
end
end
end
並具有js模板(如week.js.coffee),但以請求的操作和erb模板命名。 因此,在我的情況下為create.js.erb / new.js.erb。
但是我想得更多。 您必須首先弄清您真正需要什么。 因為一切都可以在后端或前端處理。 有幾種可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.