Ajax响应并没有改变我的视图模型

Ajax response is not changing my viewmodel

本文关键字:视图 模型 我的 改变 响应 并没有 Ajax      更新时间:2023-09-26

我绑定了一个值和一个列表,并希望在Ajax回调中对其进行更改。我在.get()中检索一个新值,但当.get()的回调实际发生时,并且我将检索到的值分配给视图模型的属性时,UI不会刷新。这是我的代码:

function SearchViewModel() {
    this.count = ko.observable(count);
    this.list = ko.observableArray(list);
    //I had count and list before I assigned.
    this.addPage = function() {
       var form = $('#form');
       var serializedData = form.serialize();
       $.get("{% url 'search:search' %}", serializedData, function(response){
           console.log(this.count); // it's undefined here.
           this.count = response.count;
           console.log(this.count); // it's the value I want to updated, e.g. 20. But UI is not refreshedenter code here
       });
   };
}

我也想在回调中更新一个列表,但现在甚至一个简单的count值都没有更新。我在stackoverflow上读到了许多相关的解决方案,并尝试了几个,但都不起作用。

尝试:

this.count(response.count);

这就行了。

有关可观测性的更多信息,请查看http://knockoutjs.com/documentation/observables.html

您的代码中还存在潜在的范围问题。当你在回调中引用这个时,你不能保证你得到了viewModel的作用域。因此,您应该在回调之外添加以下行:

var self = this;

在回调中,您应该更改为:

self.count(response.count);