我遇到了问题。我的异步返回方法永远不会被命中。我没有使用$ .getJSON的响应并在UI中显示它。 这是代码:
function SearchResult() {
var self = this;
self.Class;
self.Id;
self.Type;
self.Naam;
self.Omschrijving;
self.DocumentLink;
// added to server side object model
self.DetailUrl;
self.detailsContent = ko.observable();
self.detailsEnabled = ko.observable(false),
self.enableDetails = function () {
var aUrl = "/Search/GetDocuments?Id=" + this.Id + "&type=" + this.Type;
$.getJSON(aUrl, function (data)
{
this.detailsContent(data);
this.detailsEnabled(true);
});
};
self.disableDetails = function() {
this.detailsEnabled(false);
}
}
<!-- knockout template search results -->
<div class="list-group searchresults" data-bind="foreach: searchResults">
<div class="list-group-item" data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }">
<a data-bind="attr: { href : DetailUrl, target : '_blank'}"><h4 class="list-group-item-heading" data-bind="text: Naam"></h4></a>
<p class="list-group-item-text">
<span data-bind="text: Omschrijving"></span>
</p>
<div data-bind="visible: detailsEnabled">
<div data-bind="html: detailsContent"></div>
</div>
</div>
</div>
为了清楚起见,这从未执行过:
this.detailsContent(data);
this.detailsEnabled(true);
这一切的目的是在鼠标悬停元素时异步加载一段html。
答案 0 :(得分:3)
enableDetails
函数中的,以及获取请求的回调this
与this
中的SearchResult
不一样,您需要执行以下操作:
self.enableDetails = function () {
var aUrl = "/Search/GetDocuments?Id=" + self.Id + "&type=" + self.Type;
$.getJSON(aUrl, function (data) {
self.detailsContent(data);
self.detailsEnabled(true);
});
};
答案 1 :(得分:0)
由于某些原因,getJSON不起作用,但$ .ajax成功函数确实有效。 异步正常工作:
function SearchResult() {
var self = this;
self.Class;
self.Id;
self.Type;
self.Naam;
self.Omschrijving;
self.DocumentLink;
// added to server side object model
self.DetailUrl;
self.detailsContent = ko.observable();
self.enableDetails = function () {
var aUrl = "/Search/GetDocuments?Id=" + self.Id + "&type=" + self.Type;
$.ajax({
type: "GET",
url: aUrl,
contentType: 'application/json; charset=utf-8',
success: function (data) {
self.detailsContent(data);
},
error: function (xhr, ajaxOptions, error) {
window.location.href = "/Error/ShowError?message=" + encodeURIComponent("Onbekende fout bij het zoeken.");
}
});
};
}