如下所示,我在Rails 3.1应用程序中尝试使用link_to使用块进行POST:
views / wall / _problem.html.erb
<li data-icon="check">
<%= link_to(
url_for(
:controller => 'completed_problems',
:action => 'create',
:problem_id => "#{problem.id}"),
{:class => "wall_problem",
:confirm => "Climbed it?",
:remote => true,
:"data-type" => "json",
:method => "POST"}) do %>
<div>stuff</div>
<% end %>
</li>
views / wall / show.html.erb
<% content_for :content do %>
<div data-role="content">
<ul data-role="listview">
<%= render :partial => 'problem', :collection => @wall.live_problems.sort %>
</ul>
<% end %>
<script>
$('.wall_problem').live('ajax:success', function() {
alert("Success!");
});
</script>
该特定的POST针对以下控制器操作:
控制器/completed_problems_controller.rb
class CompletedProblemsController < ApplicationController
# POST /completed_problems
def create
@problem = Problem.find(params[:problem_id]
@completed_problem = @problem.completed_problems.build
if @completed_problem.save
render :json => { }
else
render :json => { :location => root_url}
end
end
end
从下面的日志中可以看到,POST确实可以成功完成,但是由于某种原因,该应用程序同时对完全相同的URL执行GET。
日志
Started POST "/completed_problems?problem_id=11" for 127.0.0.1 at 2011-12-11 13:13:06 -0500
Processing by CompletedProblemsController#create as JSON
Parameters: {"problem_id"=>"11"}
# SQL stuff snipped from here
Completed 200 OK in 116ms (Views: 3.0ms | ActiveRecord: 2.6ms)
Started GET "/completed_problems?problem_id=11" for 127.0.0.1 at 2011-12-11 13:13:06 -0500
Processing by CompletedProblemsController#index as HTML
Parameters: {"problem_id"=>"11"}
Rendered completed_problems/index.html.erb within layouts/application (29.6ms)
Completed 500 Internal Server Error in 36ms
这个问题听起来与jQuery ajax POST的范围类似,但会导致立即GET到相同的URL,但这使用的是jquery_ujs,我不相信自己会留下任何自定义的jQuery代码。 因此,我无法执行添加“ return false”的问题中建议的解决方案;
我怀疑问题出在以下三个位置之一:
- 我在使用link_to元素和块时语法不正确
- 我在控制器中对请求的处理不正确
- 我以某种方式使我的jquery_ujs翻了一番(我确实认为这不是真的,但是可能在这里)
编辑
缩小问题#1:
我将脚本更改为以下内容,
<script>
$('.wall_problem').live('ajax:beforeSend', function() {
return false;
});
</script>
并发现POST现在没有通过,但是GET完成了,这确认了问题似乎是AJAX处理程序正在拾取链接并将其正确提交为POST,但没有拦截浏览器提交的GET。
缩小问题2:
一开始我没有提到它,但是我正在使用Jquery-mobile。 现在,在将script标记恢复为其以前的形式,然后禁用jquery-mobile时,我再次尝试了该链接,现在它不提交GET而是提交POST。 这使我相信jquery-ujs和jquery mobile如何与链接进行交互存在一些问题。