简体   繁体   English

如何在ajax成功函数中调用函数方法?

[英]How to call function method inside ajax success function?

How to call pagePresets.setFilter() inside $.ajax(){success} method?如何在$.ajax(){success}方法中调用 pagePresets.setFilter()?

self.setFilter.call('network', data.networks); returns返回

Uncaught TypeError: Cannot read property 'call' of undefined(…)未捕获的类型错误:无法读取 undefined(...) 的属性“调用”

when self.setFilter('network', data.networks);self.setFilter('network', data.networks);

Uncaught TypeError: self.setFilter is not a function(…)未捕获的类型错误:self.setFilter 不是函数(...)

Code:代码:

function pagePresets() {
    this.loading = true;
    this.isLoading = function () {
        return this.loading;
    };
    this.setLoading = function (state) {
        this.loading = state;
        return;
    };
    /** this function loads saved filters */
    this._loadFilters = function() {
        jQuery.ajax({
            type: 'post',
            dataType: "json",
            url: 'data.json',
            success: function (data) {
                //HOW TO CALL setFilter? this solution is not working
                pagePresets.prototype.setFilter.call('network', data.networks);
            }
        });
    };
}

pagePresets.prototype.setFilter = function (target, value) {
 console.info(target + ' ' + value );
}

The call function takes as first argument a "context object". call函数将“上下文对象”作为第一个参数。 Take a deeper look at the call function here .这里更深入地了解调用函数。

In the ajax callback function this or self doesn't refere to your class object anymore.在 ajax 回调函数中, thisself不再引用您的类对象。 And pagePresets is a function class with no static properties.pagePresets是一个没有静态属性的函数类。 So you need to get the object instance.所以你需要获取对象实例。

You need to specify which instance you want to call your prototype function with.您需要指定要使用哪个实例调用原型函数。 I usualy declare a private property in my "class" wich holds a reference to the object for such scenarios where the context changes.我通常在我的“类”中声明一个私有属性,其中包含对上下文发生变化的这种场景的对象的引用。

function pagePresets() {
    //create a local variable here
    var localInstance = this;

    this.loading = true;
    this.isLoading = function () {
        return this.loading;
    };
    this.setLoading = function (state) {
        this.loading = state;
        return;
    };
    /** this function loads saved filters */
    this._loadFilters = function() {
        jQuery.ajax({
            type: 'post',
            dataType: "json",
            url: 'data.json',
            success: function (data) {
                //Use the variable here to specify the correct context.
                //the functions arguments need to be an array for the call function
                pagePresets.setFilter.call(localInstance, [ 'network', data.networks ]);
            }
        });
    };
}

pagePresets.prototype.setFilter = function (target, value) {
    console.info(target + ' ' + value );
}

you can try to invoke that in the another function like this您可以尝试在这样的另一个函数中调用它

function success() {
    pagePresets.prototype.setFilter.call('network', data.networks);
}

function error() {
    alert("error");
}


function searchEntity(id,userName, family) {
    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : "http://localhost:8080/mvc-test/rest/user/searchAll?pageNumber=1&pageSize=2&&orderBy=userName asc",
        headers: {'X-CSRF-TOKEN': getMetaContentByName('_csrf')},
        data : JSON.stringify({
            "id":id,
            "userName" : userName,
            "familyName" : family
        }),
        dataType : 'json',
        success : success,
        error : error
    });
}

Another way is to pass the parent context into the success method or delegate.另一种方法是将父上下文传递给成功方法或委托。

In the code below, onAjaxResponseReceived function is called with with the reference to the parent (class) context self from which other methods func1 and func2 can be accessed.在下面的代码中, onAjaxResponseReceived函数并使用对父(类)上下文self的引用,从中可以访问其他方法func1func2

class TestClass{
    constructor(searchUrl) {
        this.searchUrl = searchUrl;
    }

    bind() {
        self = this;

        $.ajax({
            url: self.searchUrl,
            type:"POST",
            data: data,
            success: function (responseData) {
                self.onAjaxResponseReceived(self, responseData);
            }
       });
    }

    onAjaxResponseReceived(self, data) {
        self.func1(data);
        self.func2(data);
    }

    func1(data) {
        console.log('func 1');
    }

    func2(data) {
        console.log('func 2');
    }

}

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

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