gpt4 book ai didi

ruby - Controller 无法检测到 ajax 请求

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:08 26 4
gpt4 key购买 nike

我正在使用 simple_form gem 并生成我正在指定 remote:true 选项的表单,如下所示:

<%= simple_form_for @webinar, validate: true, remote:true do |f| %>

因此,表单的输出 html 是以下片段:

<form accept-charset="UTF-8" action="/webinars" class="simple_form new_webinar" data-remote="true" data-validate="true" enctype="multipart/form-data" id="new_webinar" method="post" novalidate="novalidate"> ... </form>

正如我检查的那样,使用标准 form_for当使用 remote:true 选项时,帮助程序将 data-remote='true' 添加到表单。正如您从生成的 html 中看到的那样,当我使用 simple_form gem 时,也有这样的属性。

所以,在我的 Controller 中我有:

def create
@webinar = Webinar.new(params[:webinar])

respond_to do |format|
if @webinar.save
format.html { redirect_to @webinar, notice: 'Webinar was successfully created.' }
format.js
format.json { render json: @webinar, status: :created, location: @webinar }
else
format.html { render action: "new" }
format.json { render json: @webinar.errors, status: :unprocessable_entity }
end
end
end

但是,始终使用 format.html。我做错了什么?

编辑:

我已经使用 logger.debug request.format 来检查要求的实际格式是什么,在日志文件中是:

text/html

所以,问题一定出在 simple_form 生成的表单中 - 当我们使用“data-remote=true”时,哪里出了问题?

最佳答案

您将 format.json|format.htmlremote: true 混淆了。两者不同。 remote: true 的存在并不意味着 format.json

format.json 不表示该 URL 是通过 javascript 调用的。这仅表示客户端需要 JSON 输出。即它不表示输入来自何处,它表示需要什么输出。

remote:true 的一般用途是,您无需重新加载页面,而是将表单作为 Ajax 请求提交,然后在 JQuery 弹出窗口或其他内容中显示响应。但是,如果您想将响应显示为 JQuery 弹出窗口 - 您需要 HTML 输出,而不是 JSON 输出,对吧?

有些人使用 remote: true 在弹出窗口中加载 HTML 内容。您的用例是执行 remote: true 但您需要 JSON 格式的数据。 Rails 无法为您做出这些决定。它默认将请求发送到 /webinars 并期望您处理 HTML 响应。如果您真的想要 JSON 响应 - 然后自定义 Ajax 请求发布到的 URL:

simple_form_for @webinar, url: webinar_path(format: :json), .....

如果您执行上述操作,现在将以 JSON 格式调用网络研讨会 Controller 。

总体:

  • remote:true 可以与 format.htmlformat.json 一起使用
  • Rails 应用程序中的大多数用例是像往常一样将 remote: true 作为 Controller 请求进行处理,呈现部分 HTML 模板(即仅响应内容,没有整体页面布局/导航/等)并将其作为 HTML 发回以显示在弹出窗口中
  • 大多数人只是一揽子处理远程回调并显示 JQuery 弹出窗口。因此他们不需要为每个远程表单编写单独的代码
  • 所以默认情况下,Rails 调用format.html 进行远程请求
  • 如果您特别需要 format.json,并且您真的想在客户端手动处理 JSON,请相应地更改 URL。但这不是大多数用例
  • 发出 Ajax 请求并不意味着内容类型是 JSON。它是使用 Javascript 发出的 HTML 请求。例如在 jquery $.ajax方法,检查这两个选项:acceptdataType。如果你真的想发送 Accepts: application/json header ,那么你必须在发出 Ajax 请求时手动指定(或者你需要以 .json 结束 url如果它是 Rails 应用程序)。
  • 因此,即使您向 /webinars 发出正常的 Ajax 请求,例如 $.ajax('/webinars', ...) - 它也不会成功到 format.json !它仍然只会转到 format.html。如果你真的想要 JSON 格式,那么你必须说 $.ajax('/webinars', { accepts: 'application/json' }),或者你必须说 $.ajax( '/webinars.json')

编辑:小的澄清

关于ruby - Controller 无法检测到 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com