AJAX:成功与阿贾克斯:完整的回调中不使用的Rails UJS时,工作回调、中不、完整、工作

2023-09-11 00:41:05 作者:失信的承诺

我有一个链接,当我点击它会触发一个AJAX调用然后更换这个环节由另一条链路,表示例如原文链接是加为好友,当我点击这个链接它会发送一个Ajax请求add_friend行动,那么如果朋友加入上述将被另一个链接取消申请所取代,我使用UJS该链接:

I have a link that when i click on it will trigger an ajax call then replace this link by another link, says for example the original link is "add friend", when i click this link it will send an ajax request to add_friend action then if the friend is added the link above will be replaced by another link "cancel request", i use ujs for that :

$("#link_for_friend").html("<%= escape_javascript(render('users/cancel_link')) %>")

当我尝试添加回调(:成功:完成)它不工作,我试着用:beforeSend喜欢它的工作原理如下:

when i try to add callback (:success and :complete) it doesn't works, i tried with :beforeSend like the following it works :

$(document).ready ->
  $("#my_link").on "ajax:beforeSend", ->
    alert("hello")

有成功和完整的回调的解决方案?

there is a solution for success and complete callback ?

请注意:我的想法是显示一个loader.gif时ajaxStart被触发,则隐藏它,当阿贾克斯:完整的回调触发至少,也当有一些错误我想告诉它,当阿贾克斯:触发误差

note : my idea is to show an loader.gif when ajaxStart is triggered then hide it when ajax:complete callback is triggered at least , also if there is some error i want to show it when ajax:error is triggered

更新

我试图通过移动code里面action.js.erb到js文件是这样解决的:

I tried to solve this by moving the code inside action.js.erb to js file like this :

  $(document).ready ->
  $(document).on("ajax:success", "a.invitation-box", ->
    $("#link_for_friend").html("<%= escape_javascript(render('users/cancel_link')) %>")
  ).on "ajax:error", "a.invitation-box", ->
    alert "error"

但这样一来它不可能把渲染(用户/ cancel_link')内的JS文件

but this way its not possible to put render('users/cancel_link') inside a JS file

推荐答案

我有同样的问题,这个问题是不是与阿贾克斯:成功或AJAX:完成回调。 的问题是,显示装载GIF图像时,替换容器的内容,包括链接本身。因此,在其应用成功的元素,完整的回调不是DOM的一部分了,这就是为什么回调不激发。

I had the same issue, and the problem is not with ajax:success or ajax:complete callback. The problem is that when displaying the loading gif image, you replace the content of the container, including the link itself. So the element on which you apply the success, complete callback is not part of the DOM anymore, that's why the callback is not fired.

一个解决办法是隐藏元素,并添加加载图像,像下面这样:

One solution would be to hide the element and append the loading image, like following:

$('#my_link').on "ajax:send", (event, xhr, settings) ->
        $('#my_link').hide()
        $("#my_link_container").append("<image src = 'img.gif' />")

那么成功和完整的回调将被解雇。 希望它可以帮助别人:)

Then the success and complete callback will be fired. Hope it helps somebody :)