【问题标题】:Rails JQuery sending GET instead of POST requestRails JQuery 发送 GET 而不是 POST 请求
【发布时间】:2014-03-04 01:28:56
【问题描述】:

我被一个 Rails 问题困扰了几天,一直找不到解决方案。我的代码曾经可以工作,但 javascript 发生了一些重大更改(必需)并且它不再工作。

我的用户可以参加和退出活动。这需要用户单击按钮,然后发送发布请求,但由于某种原因,请求被作为获取请求处理,并且由于获取请求没有路由(需要发布)而失败。

查看:

    <% if @competition.users.exclude?(@user)  %>
      <%= link_to 'Attend Competition', attend_competition_path(@competition.id), :method => :post %>
    <% else %>
      <%= link_to 'Withdraw', withdraw_competition_path(@competition.id), :method => :post %>

应用程序.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require_tree .

application.html.erb

<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>

routes.rb

  resources   :competitions do
    post 'attend', on: :member
  end
  resources   :competitions do
    member do 
      post 'withdraw'
    end
  end

控制器:

def attend
@competition = Competition.find(params[:id])
if @competition.users.include?(current_user)
  flash[:error] = "You're already attending this competition."
elsif current_user.daily == []
  flash[:error] = "You must have a working device to compete."
else
  current_user.competitions << @competition
  flash[:success] = "Attending competition!"
end
redirect_to @competition
end


def withdraw
p "WITHDRAWING"
@competition    = Competition.find(params[:id])
p @competition
attendee = Attendee.find_by_user_id_and_competition_id(current_user.id, @competition.id)
if attendee.blank?
  flash[:error] = "No current attendees"
else
  attendee.delete
  flash[:success] = 'You are no longer attending this competition.'
end
p attendee
redirect_to @competition
end

实际错误:

ActionController::RoutingError (No route matches [GET] "/competitions/9/withdraw"):

谢谢

** 额外的 **

完整的show.view

<p id="notice"><%= notice %></p>
<p>
  <%= @competition.title %>
</p>
<p>
  <b>Length:</b>
  <%= @competition.length %>
</p>
  <b>Start:</b>
  <%= @competition.start.strftime("%d %m %Y") %>
</p>
  <b>End:</b>
  <%= @competition.end.strftime("%d %m %Y") %>
</p>
<p><strong>Attendees: </strong>
    <% if @competition.users.exclude?(@user)  %>
      <%= link_to 'Attend Competition', attend_competition_path(@competition.id), :method => :post %>
    <% else %>
      <%= link_to 'Withdraw', withdraw_competition_path(@competition.id), :method => :post %>
    <% end %>
</p>
<% a = 1 %>
<% for attendee in @competition.users %>
  <p2><strong><%= a %> </strong><%= link_to attendee.name, attendee %></p2>
  <% if attendee.daily != [] %>
   <p><%= attendee.daily.first(7).sum %></p>
  <% end %>
  <% a = a + 1 %>
<% end %>
</br>


<%= link_to 'Edit', edit_competition_path(@competition) %> |
<%= link_to 'Back', competitions_path %>

Rails 的 HTML 输出

<a href="/competitions/4/withdraw" data-method="post" rel="nofollow">Withdraw</a>

** MOAR **

日志中的完整错误

ActionController::RoutingError (No route matches [GET] "/competitions/6/withdraw"):
  actionpack (3.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  railties (3.2.3) lib/rails/rack/logger.rb:26:in `call_app'
  railties (3.2.3) lib/rails/rack/logger.rb:16:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/request_id.rb:22:in `call'
  rack (1.4.5) lib/rack/methodoverride.rb:21:in `call'
  rack (1.4.5) lib/rack/runtime.rb:17:in `call'
  activesupport (3.2.3) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.4.5) lib/rack/lock.rb:15:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/static.rb:62:in `call'
  railties (3.2.3) lib/rails/engine.rb:479:in `call'
  railties (3.2.3) lib/rails/application.rb:220:in `call'
  rack (1.4.5) lib/rack/content_length.rb:14:in `call'
  railties (3.2.3) lib/rails/rack/log_tailer.rb:14:in `call'
  rack (1.4.5) lib/rack/handler/webrick.rb:59:in `service'
  /Users/Marcus/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /Users/Marcus/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /Users/Marcus/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'


  Rendered /Users/Marcus/.rvm/gems/ruby-1.9.3-p448@rails3tutorial2ndEd/gems/actionpack-3.2.3/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.5ms)

来自浏览器的 HTML:

<a href="/competitions/3/withdraw" data-method="post" rel="nofollow">Withdraw</a>

整页[可能很长]:

<html><head>
<title>BOTB</title>
<link data-turbolinks-track="true" href="/assets/application.css" media="all" rel="stylesheet" type="text/css">
<script data-turbolinks-track="true" src="/assets/application.js" type="text/javascript">    </script><style type="text/css"></style>
<meta content="authenticity_token" name="csrf-param">
<meta content="Cl7ar8gwVcRsJzrKjp92KB6p6PihvVu0jAwngi18dWU=" name="csrf-token">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

  <style id="clearly_highlighting_css" type="text/css">/* selection */ html.clearly_highlighting_enabled ::-moz-selection { background: rgba(246, 238, 150, 0.99); } html.clearly_highlighting_enabled ::selection { background: rgba(246, 238, 150, 0.99); } /* cursor */ html.clearly_highlighting_enabled {    /* cursor and hot-spot position -- requires a default cursor, after the URL one */    cursor: url("chrome-extension://pioclpoplcdbaefihamjohnefbikjilc/clearly/images/highlight--cursor.png") 14 16, text; } /* highlight tag */ em.clearly_highlight_element {    font-style: inherit !important; font-weight: inherit !important;    background-image: url("chrome-extension://pioclpoplcdbaefihamjohnefbikjilc/clearly/images/highlight--yellow.png");    background-repeat: repeat-x; background-position: top left; background-size: 100% 100%; } /* the delete-buttons are positioned relative to this */ em.clearly_highlight_element.clearly_highlight_first { position: relative; } /* delete buttons */ em.clearly_highlight_element a.clearly_highlight_delete_element {    display: none; cursor: pointer;    padding: 0; margin: 0; line-height: 0;    position: absolute; width: 34px; height: 34px; left: -17px; top: -17px;    background-image: url("chrome-extension://pioclpoplcdbaefihamjohnefbikjilc/clearly/images/highlight--delete-sprite.png"); background-repeat: no-repeat; background-position: 0px 0px; } em.clearly_highlight_element a.clearly_highlight_delete_element:hover { background-position: -34px 0px; } /* retina */ @media (min--moz-device-pixel-ratio: 2), (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {    em.clearly_highlight_element { background-image: url("chrome-extension://pioclpoplcdbaefihamjohnefbikjilc/clearly/images/highlight--yellow@2x.png"); }    em.clearly_highlight_element a.clearly_highlight_delete_element { background-image: url("chrome-extension://pioclpoplcdbaefihamjohnefbikjilc/clearly/images/highlight--delete-sprite@2x.png"); background-size: 68px 34px; } } </style><style>[touch-action="none"]{ -ms-touch-action: none; touch-action: none; }[touch-action="pan-x"]{ -ms-touch-action: pan-x; touch-action: pan-x; }[touch-action="pan-y"]{ -ms-touch-action: pan-y; touch-action: pan-y; }[touch-action="scroll"],[touch-action="pan-x pan-y"],[touch-action="pan-y pan-x"]{ -ms-touch-action: pan-x pan-y; touch-action: pan-x pan-y; }</style></head>
  <body style="">
    <header class="navbar navbar-fixed-top navbar-inverse">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" id="logo">Battle Of The Bands</a>
      <nav>
        <ul class="nav pull-right navbar-nav " id="menu">
          <li><a href="/">Home</a></li>
          <li><a href="/competitions">Competition</a></li>
            <li><a href="/users">Users</a></li>
            <li id="fat-menu" class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                Account <b class="caret"></b>
              </a>
              <ul class="dropdown-menu">
                <li><a href="/users/1">Profile</a></li>
                <li><a href="/devices">Connect Device</a></li>
                <li><a href="/competitions/new">Create Competition</a></li>
                <li><a href="/users/1/edit">Settings</a></li>
                <li class="divider"></li>
                <li>
                  <a href="/signout" data-method="delete" rel="nofollow">Sign out</a>
                </li>
              </ul>
            </li>
        </ul>
      </nav>
    </div>
  </div>
</header>
    <div class="container">
      <p id="notice"></p>

<p>
  Tester March 8
</p>

<p>
  <b>Length:</b>
  5
</p>
  <b>Start:</b>
  03 03 2014
    <p></p>
  <b>End:</b>
  03 03 2014
<p></p>
<p><strong>Attendees: </strong>
      <a href="/competitions/3/withdraw" data-method="post" rel="nofollow">Withdraw</a>
</p>
  <p2><strong>1 </strong><a href="/users/1">Marcus Smith</a></p2>
   <p>49774</p>
<br>


<a href="/competitions/3/edit">Edit</a> |
<a href="/competitions">Back</a>

      <footer class="footer">
  <small>
    by <a href="http://www.twitter.com/_mhsmith_"> Marcus Smith</a>
  </small>
  <nav>
    <ul>
      <li><a href="/about">About</a></li>
    </ul>
  </nav>
</footer>
      <!-- <pre class='debug_dump'>--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
action: show
controller: competitions
id: '3'
    </pre> -->
    </div>

</body></html>

【问题讨论】:

  • 你能分享一下提取链接的 HTML 吗?如果 Rails 正在做它的事情,它将是一个表单。顺便说一下(可能只是复制/粘贴),您的视图中没有 end。只是提到,因为一切看起来都正确,所以我们必须寻找奇怪的东西。
  • 页面上有任何 javascript 错误?
  • Javascript 错误不会出现在 Rails 日志中。您必须在浏览器中打开控制台视图(在 chrome 中,您可以右键单击,检查元素,然后转到“控制台”选项卡,然后刷新页面)。 Javascript 错误将出现在控制台中
  • 当您看到“GET http...404(未找到)”时,问题已经过去了。这意味着链接没有被 jquery_ujs 解释。只需加载页面并不要点击撤回链接。在点击链接之前会显示影响事物的 Javascript 错误。
  • 请分享浏览器生成的 HTML,以便我们确保 rails 使用您提供的参数生成正确的 FORM 标记。

标签: javascript jquery ruby-on-rails ruby-on-rails-3


【解决方案1】:

我怀疑这是因为您没有包含 jquery_ujs.js。

// application.js
//
//= require jquery
//= require jquery_ujs

在您的 application.js 清单中,您应该包含 jquery_ujs - 由于标签中的 data-method 字段,它不会将 GET 请求转换为 POST 的不显眼的 JavaScript 代码。

如果您确实包含了 jquery_ujs.js,那么sevenseacat 关于 javascript 错误的评论可能就是它 - 如果您在执行 jquery_ujs.js 之前出现任何 javascript 错误,它会无法解释您的链接。

【讨论】:

  • 我在 application.js 文件中包含 jquery_ujs。我刚刚从日志中包含了整个错误,也许这会有所帮助。
【解决方案2】:

我不知道是否有人会看到这一点,因为自从提出问题以来已经过去了很长时间,但我遇到了同样的问题,所以如果有人正在寻找答案并且 jquery-ujs 不是问题,这是最终为我解决的问题 - 仔细检查您的代码并确保您没有

$(document).unbind('click')...

代码中的任何位置。这会导致 Rails 用于将 GET 请求转换为 POST 或 DELETE 请求所需的 JavaScript 无法运行。希望这有助于解决这个困扰我很长时间的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多