我有这段代码:
t._teacherOptions = ko.observable();
function getTeacherList() {
$.ajax({
type: "POST",
url: "/webservices/Service.asmx/GetTeachers",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(i) {
if (i.d) {
console.log(i.d);
return t._teacherOptions(i.d);
}
},
error: function(n) {
u(n);
}
});
}
t.TeacherOptions = ko.computed(function() {
getTeacherList();
return t._teacherOptions();
});
然后是我的html:
<select data-bind="options: $root.TeacherOptions(), value: Id, optionsText: 'Name'"></select>
由于某种原因,当打开页面时,获取教师列表的功能不断循环而不停。
我能够获得所需的结果,但是循环不断进行,我需要停止该过程。我在这里做错什么了吗?
您循环不断,因为您的TeacherOptions
(是computed
)访问了_teacherOptions
(因此创建了依赖项),并且因为您正在更改_teacherOptions
回调中的success
的值Ajax调用,TeacherOptions
再次被评估(因为它取决于_teacherOptions
),并再次发出Ajax请求。
尝试在getTeacherList()
之外呼叫computed
:
t._teacherOptions = ko.observable();
function getTeacherList() {
$.ajax({
type: "POST",
url: "/webservices/Service.asmx/GetTeachers",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(i) {
if (i.d) {
console.log(i.d);
return t._teacherOptions(i.d);
}
},
error: function(n) {
u(n);
}
});
}
getTeacherList();
t.TeacherOptions = ko.computed(function() {
return t._teacherOptions();
});