gpt4 book ai didi

javascript - 通过 javascript 发送 Rails PUT 请求

转载 作者:行者123 更新时间:2023-11-28 02:47:24 26 4
gpt4 key购买 nike

如何通过 Rails 中的 javascript 向操作发送 PUT 请求?以下是我在 .html.erb 文件中执行此操作的方法:

<%= link_to "Check", check_task_path(task), :method => :put %>

我如何在 JavaScript 中执行此操作?

最佳答案

添加 :remote => true 以在链接上启用 ajax。

<%= link_to "Check", check_task_path(task), :method => :put, :remote => true %>

假设您想要在index页面中检查任务。

index.html.erb

<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>

tasks_controller.rb

  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

check.erb.js

<% if @task.errors.empty? %>
jQuery("#completed_<%= @task.id %>").html("true.");
<% else %>
alert("Task could not be saved.");
<% end %>

路线.rb

  resources :tasks do
member do
put 'check'
end
end

application.html.erb

<!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>

关于javascript - 通过 javascript 发送 Rails PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4573028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com