简体   繁体   English

jQuery Ajax .ajaxSuccess()事件没有触发

[英]jQuery Ajax .ajaxSuccess() event not firing

I have a native javascript object, that I would like to assign the .ajaxSuccess callback to. 我有一个原生的javascript对象,我想将.ajaxSuccess回调分配给。 The purpose of this is because I want my data model to update after an ajax call succeeds, but I don't want to make my data model global to the entire javascript file. 这样做的目的是因为我希望我的数据模型在ajax调用成功后更新,但我不想让我的数据模型全局到整个javascript文件。 And yes, I checked to make sure my jQuery is included before my script file. 是的,我检查确保我的jQuery包含在我的脚本文件之前。

Here is the code: 这是代码:

$("#formButtonAddLink").click(function() {
    $.ajax({
        type: "POST",
        url: "ajax/addlink",
        data: {content: $("#formInputLinkContent").val(), subject: $("#formInputLinkSubject").val()},
        dataType: "json",
        error: function() {
            alert("An ajax error occured adding link")
        }
    });
    return false; //prevents html form submit
})

$(document).ready(function(){
    var links = new Links(20,0);
    $(links).ajaxSuccess(function() {
        console.log("Hey.")    //This does not work.
    });
    $(document).ajaxSuccess(function() {
        console.log("Document hey.")   //This shows up.
    });
});

The basic idea of ajaxSuccess() is: ajaxSuccess()的基本思想是:

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. 每当Ajax请求成功完成时,jQuery就会触发ajaxSuccess事件。 Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time. 已经使用.ajaxSuccess()方法注册的任何和所有处理程序都会在此时执行。

As far as I understand it from the documentation you can only attach the ajaxSuccess() event handler to an element , not a JavaScript object. 据我所知,从文档中你只能将ajaxSuccess()事件处理程序附加到一个元素 ,而不是一个JavaScript对象。 That is why it works when attaching the event handler to the document . 这就是将事件处理程序附加到document时的工作原理。

We can attach our event handler to any element. 我们可以将事件处理程序附加到任何元素。

In this case if you have something similar to: 在这种情况下,如果你有类似的东西:

<div class="links"></div>

You could do: 你可以这样做:

$(document).ready(function(){
    $(".links").ajaxSuccess(function() {
        console.log("Hey.")
        // use links in here:
        var links = new Links(20,0);
    });
});

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

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