You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

data-turbo-stream未正确设置Accept标头问题求助

解决Rails Turbo表单提交后显示原始Turbo流的问题

问题根源

按下回车提交GET表单时,Turbo未发送Turbo流对应的Accept: text/vnd.turbo-stream.html请求头,导致浏览器将控制器返回的Turbo流当作普通HTML渲染成新页面。原表单的data: { turbo_stream: true }仅对链接生效,不适用于表单场景。

解决方案

方案1:修改表单属性,强制Turbo处理提交并指定Accept头

更新表单代码,添加data-turbo="true"确保Turbo接管表单提交逻辑,同时用data-type="turbo-stream"指定请求接受Turbo流格式:

<%= form_with url: suggestions_path, method: :get, data: { turbo: true, type: "turbo-stream" } do |form| %>
    <%= form.search_field :query %>
<% end %>
<div id="salesMemberSuggestions"></div>

方案2:控制器强制设置响应Content-Type

如果表单属性调整无效,可在控制器中主动指定响应的Content-Type为Turbo流格式,确保浏览器正确识别返回内容:

def index
  if params[:query].present?
    # 处理API数据逻辑
    @suggestions = # 格式化后的API数据
    render(
      turbo_stream: turbo_stream.update(
        "salesMemberSuggestions",
        partial: "copilot/suggestions/suggestions",
        locals: { suggestions: @suggestions }
      ),
      content_type: "text/vnd.turbo-stream.html"
    )
  else
    render(
      turbo_stream: turbo_stream.update("salesMemberSuggestions", ""),
      content_type: "text/vnd.turbo-stream.html"
    )
  end
end

验证要点

  • 检查网络请求的Accept头是否包含text/vnd.turbo-stream.html
  • 确认控制器响应的Content-Type为text/vnd.turbo-stream.html
  • 确保页面中存在id="salesMemberSuggestions"的目标元素
  • 验证Turbo已正确引入到应用(如application.js中包含import "@hotwired/turbo-rails")

内容的提问来源于stack exchange,提问作者Gabe Braden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 23:17:08