gpt4 book ai didi

javascript - form_for 未触发 Ajax 事件

转载 作者:行者123 更新时间:2023-11-28 06:26:09 25 4
gpt4 key购买 nike

我对 Rails 中表单的 JS 事件有一个小问题。事实上我做了一个表单,但是提交表单时事件没有被触发,我不明白我做错了什么:/

这是我的表格:

<%= form_for(@server, remote: true, method: "get", url: "/servers", html: { id: "edit_server_form" }) do |f| %>
Name: <%= f.text_field :name, class: "form-control" %>
<%= f.submit %>
<% end %>

还有我的 JS:

edit_server_form = $("#edit_server_form")
edit_server_form.bind 'ajax:before', (e) ->
console.log 'ajax:before'
edit_server_form.bind 'ajax:success', (event, data, status, xhr) ->
console.log 'ajax:success'
edit_server_form.bind 'ajax:failure', (xhr, status, error) ->
console.log 'ajax:failure'
edit_server_form.bind 'ajax:error', (xhr, status, error) ->
console.log 'ajax:error'
edit_server_form.bind 'ajax:complete', ->
console.log 'ajax:complete'

这些事件均未触发,但查询已发送:/

Screen Query sent

感谢您的帮助!

最佳答案

看起来可能与您的 JQuery delegation 有关:

#app/assets/javascripts/application.js
$(document).on("ajax:before", "#edit_server_form", (e) ->
console.log 'ajax:before'
).on("ajax:success", "#edit_server_form", (event, data, status, xhr) ->
console.log 'ajax:success'
).on("ajax:failure", "#edit_server_form", (xhr, status, error) ->
console.log 'ajax:failure'
).on("ajax:error", "#edit_server_form", (xhr, status, error) ->
console.log 'ajax:error'
).on("ajax:complete", "#edit_server_form" ->
console.log 'ajax:complete'

--

您遇到的问题不是缺少请求,而是其日志记录。

Beginning”消息表明请求正在被触发。

因为 Turbolinks 会导致 DOM 出现问题(它会刷新 body 而不更新 JS/资源),所以您必须delegate来自一个永远存在的元素。我们使用 document,尽管效率很低。

<小时/>

您还最好在表单中使用以下内容:

<%= form_for @server, remote: true, url: servers_path, method: "get", html: { id: "edit_server_form" } do |f| %>

关于javascript - form_for 未触发 Ajax 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35121048/

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