нокаут: Ajax-запрос отменяется - PullRequest
0 голосов
/ 13 сентября 2018

Я хочу запретить предыдущий запрос ajax при запуске нового запроса. Я делаю это, как показано ниже. Но это не работает.

Я добавил код в функцию beforeSend () для отмены предыдущего запроса. Но это не работает.

Пожалуйста, помогите мне решить эту проблему.

JQuery:

return Component.extend({
    defaults: {
        changeTextValue: ko.observable(),
        currentRequest: ko.observable(),
        anotherObservableArray: [],
        subscription: null,
        tracks: {
            changeTextValue: true
        }
    },
    initialize: function() {
        this._super();
    },
    doSomething: function(config) {
        var self = this;
        if (this.subscription)
            this.subscription.dispose();

        this.subscription = this.changeTextValue.subscribe(function(newValue) {
            this.currentRequest = $.ajax({
                url: urlBuilder.build('abc/temp/temp'),
                type: 'POST',
                data: JSON.stringify({
                    'searchtext': newValue
                }),
                global: true,
                contentType: 'application/json',
                beforeSend: function(jqXHR) {
                    console.log("before Ajax send");
                    console.log(this.currentRequest);
                    if (this.currentRequest != null) {
                        this.currentRequest.abort();
                    }
                },
                success: function(response) {
                    var json_data = JSON.parse(response);
                    self.autocompleteData.removeAll();
                    $.each(json_data, function(key, val) {
                        self.autocompleteData.push({
                            productID: val.productID
                        });
                    });
                },
                error: function(jqXHR, exception) {
                    alert("Not OK!")
                }
            });
        });
    },
});
ko.applyBindings(new CeremonyViewModel());

1 Ответ

0 голосов
/ 13 сентября 2018

Итак, я предполагаю, что вы хотите отменить предыдущий запрос при повторном вызове функции subscribe, верно?

В этом случае попробуйте прервать его, если subscribe вызывается снова.

return Component.extend({
    defaults: {
        changeTextValue: ko.observable(),
        currentRequest: null,
        anotherObservableArray: [],
        subscription: null,
        tracks: {
            changeTextValue: true
        }
    },
    initialize: function() {
        this._super();
    },
    doSomething: function(config) {
        var self = this;
        if (this.subscription)
            this.subscription.dispose();

        this.subscription = this.changeTextValue.subscribe(function(newValue) {
            if (self.currentRequest) {
                self.currentRequest.abort();
            }
            self.currentRequest = $.ajax({
                url: urlBuilder.build('abc/temp/temp'),
                type: 'POST',
                data: JSON.stringify({
                    'searchtext': newValue
                }),
                global: true,
                contentType: 'application/json',
                success: function(response) {
                    var json_data = JSON.parse(response);
                    self.autocompleteData.removeAll();
                    $.each(json_data, function(key, val) {
                        self.autocompleteData.push({
                            productID: val.productID
                        });
                    });
                },
                error: function(jqXHR, exception) {
                    alert("Not OK!")
                }
            });
        });
    },
});
ko.applyBindings(new CeremonyViewModel());
...