gpt4 book ai didi

javascript - Rails 使用 AJAX 请求响应不同格式

转载 作者:行者123 更新时间:2023-11-28 07:05:20 25 4
gpt4 key购买 nike

我正在尝试理解 Rails 中的 AJAX 请求。我有一个当前使用远程提交的表单:true。如果请求成功,我想用 HTML 重定向进行响应,如果请求不成功,我想用 Javascript 运行错误消息。但是,无论结果是什么,请求似乎都期望返回 .html。

respond_to do |format|
if conversation
format.html { redirect_to(conversation_path(conversation)) }
else
format.js
end
end

这是在我保存 AJAX 上的对话调用后调用的。成功保存后,路径 HTML 会正确发回,但不会在客户端上呈现。但如果保存不成功,它需要 .html 并抛出错误。我如何接受 .js 作为响应?我的目标是在调用不成功时弹出错误,在调用成功时弹出redirect_to。

编辑:我的form_for:

<%= form_for :conversation, url: :conversations, remote: true, html: { class: "conversation-form" } do |f| %>

最佳答案

这里有一个建议替代您的最终目标 - 在 Controller 中,将 format.html 条目放入您的 respond_to block 中。另外,将 conversation 设置为 View 模板可以访问的实例变量:

class YourController < ActionController::Base
def your_action
# awesome code doing stuff with a conversation object goes here

@conversation = conversation

respond_to do |format|
format.js # your_action.js.erb
end
end
end

然后,将重定向逻辑放入您的 JavaScript View 模板中(对于上面的示例:app/views/.../your_action.js.erb):

<% if @conversation.errors.any? # or whatever condition you want to show a popup for %>

// put your javascript popup code here
alert('Errors happened!');

<% else %>

// this is how you do a redirect using javascript:
window.location.href = "<%= conversation_path( @conversation ) %>";

<% end %>

希望这有帮助!

关于javascript - Rails 使用 AJAX 请求响应不同格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757163/

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