如何在Rails中通过javascript向动作发送PUT请求?以下是我在.html.erb文件中的操作方法:
<%= link_to "Check", check_task_path(task), :method => :put %>
我如何在javascript中执行此操作?
答案 0 :(得分:1)
添加:remote => true
以在链接上启用ajax。
<%= link_to "Check", check_task_path(task), :method => :put, :remote => true %>
假设您需要index
页面中的检查任务。
<table>
<tr>
<th>Name</th>
<th>Completed</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<% @tasks.each do |task| %>
<tr>
<td><%= task.name %></td>
<td id="completed_<%= task.id %>"><%= task.completed %></td>
<td><%= link_to 'Show', task %></td>
<td><%= link_to 'Edit', edit_task_path(task) %></td>
<td><%= link_to 'Destroy', task, :confirm => 'Are you sure?',
:method => :delete %></td>
<td><%= link_to "Check", check_task_path(task), :method => :put,
:remote => true, :class => :check_task %></td>
</tr>
<% end %>
</table>
def check
@task = Task.find(params[:id])
@task.completed = true
respond_to do |format|
if @task.update_attributes(params[:task])
format.html { redirect_to(@task,
:notice => 'Task was successfully updated.') }
format.xml { head :ok }
format.js
else
format.html { render :action => "edit" }
format.xml { render :xml => @task.errors,
:status => :unprocessable_entity }
format.js
end
end
<% if @task.errors.empty? %>
jQuery("#completed_<%= @task.id %>").html("true.");
<% else %>
alert("Task could not be saved.");
<% end %>
resources :tasks do
member do
put 'check'
end
end
<!DOCTYPE html>
<html>
<head>
<title>Tada</title>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" %>
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>