简体   繁体   English

Ajax事件未触发form_for

[英]Ajax events not fired form_for

I have a little issue with events in JS for a form in Rails. 我对JS中的事件在Rails中的表单有一点问题。 In fact I done a form, but events are not fired when the form is submitted, I don't understand what I did wrong :/ 实际上我已经完成了表单,但是提交表单时不会触发事件,我不明白自己做错了什么:/

Here is my form: 这是我的表格:

<%= 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 %>

And my JS: 而我的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'

None of these events is triggered but the query is sent :/ 这些事件均不会触发,但会发送查询:/

屏幕查询已发送

Thanks for your help ! 谢谢你的帮助 !

This looks like it could be to do with your JQuery delegation : 看起来可能与您的JQuery委托有关

#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'

-- -

The problem you have isn't a lack of request, but its logging. 您遇到的问题不是缺少请求,而是日志记录。

The " Beginning " message suggests that a request is being fired. 在“ Beginning ”的消息表明,一个请求解雇。

Because Turbolinks causes issues with the DOM (it refreshes the body without updating the JS / assets), you have to delegate from an element which is always going to remain present. 因为Turbolinks会导致DOM问题(它会刷新body而不更新JS /资产),所以您必须从始终保持存在的元素进行委派 We use document , although it's quite inefficient. 我们使用document ,尽管效率很低。


You'd also do well to use the following with your form: 您也最好在表单中使用以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM