【问题标题】:Send Rails PUT request through javascript通过 javascript 发送 Rails PUT 请求
【发布时间】:2011-01-01 02:47:03
【问题描述】:

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

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

我将如何在 javascript 中执行此操作?

【问题讨论】:

    标签: javascript controller ruby-on-rails-3 action put


    【解决方案1】:

    添加 :remote =&gt; 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 %>
    

    routes.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 向控制器操作发送任何(POST 或 GET)请求?
    • 好的,但是当用户单击复选框时,我尝试仅在 javascript 中执行此操作(因此是任务的检查功能)。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2018-04-09
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多