我刚刚在一台新机器上安装了一个 Rails 3.0.3 项目,我发现了一些与 form_tag :remote => true 相关的奇怪行为。请求中似乎设置了错误的 Accept header ,因此它不是作为 AJAX/JS 请求出现的,而是作为 HTML 请求出现的。在我的生产服务器上,Accept header 设置正确:
Accept:*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript
规范:
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-linux]
Rails 3.0.3
但是,在我正在设置的新机器上,它看起来像这样:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
规范:
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]
Rails 3.0.3
这是生成表单的代码(在 _request.html.erb 中)
<div id='request-translation'>
<h2 class="tr-req left"><%= t( 'user.translation_requests.request' ) %></h2>
<%= form_tag( request_translation_artist_song_path( @artist, @song ),
:method => :post,
:remote => true,
:class => 'left',
:style => 'margin-left: 20px;' ) %>
<%= languages_combobox_large( @into_languages, 'language_id' ).html_safe %>
</form>
</div>
当然,在我的 Controller 中,我只响应 format.js,但请求以 format.html 形式出现。我认为 :remote => true 处理了这个问题。为表单生成的 HTML 看起来也不错:
<form accept-charset="UTF-8" action="/xxx/request_translation" class="left" data-remote="true" format="js" method="post" style="margin-left: 20px">
最佳答案
请确保您在 HTML header 中包含 jquery.js 和 *jquery_ujs.js*。
jquery_ujs 负责通过设置了 data-remote 属性的 AJAX 发送表单。由于它不显眼,因此即使没有它,该表格也能正常工作。但它是通过普通页面请求发送的。
关于jquery - Rails 3.0 form_tag w/remote 不正确接受 : header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9494166/