我在通过$ .ajax jquery检索数据时遇到问题,并通过knockout将它们绑定到表中。当我运行下面的代码,通过$ .ajax检索数据时,表是空的。我可以看到数据在observableArray中,但没有被链接。当用$ .getJSON更改$ .ajax时,表格将被填充。
按照代码:
var Papel = function (data) {
var self = this;
self.ID = data.ID;
self.Nome = ko.observable(data.Nome);
self.Descricao = ko.observable(data.Descricao);
};
var PapelViewModel = function () {
var self = this;
self.Papeis = ko.observableArray();
self.Item = ko.observable();
self.Erro = ko.observable();
self.LoadPapeis = function(){
//Quando troco por $.getJson funciona perfeitamente
ajaxRequest("get", "home/list")
.done(function (datas) {
var mappedList = $.map(datas, function (item) { return new Papel(item) });
self.Papeis = mappedList;
}).fail(function (a, b, c) { alert(c) });
}
self.LoadPapeis()
function ajaxRequest(type, url, data) { // Ajax helper
var options = {
dataType: "json",
contentType: "application/json",
cache: false,
type: type,
data: data ? data.toJson() : null
};
var antiForgeryToken = $("#antiForgeryToken").val();
if (antiForgeryToken) {
options.headers = {
'RequestVerificationToken': antiForgeryToken
}
}
return $.ajax(url, options);
}
;
}
ko.applyBindings(new PapelViewModel());

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="cont">
<table>
<thead>
<tr><th>ID</th><th>Nome</th><th>Descricao</th></tr>
</thead>
<tbody data-bind="foreach: Papeis">
<tr>
<td data-bind="text: ID"></td>
<td data-bind="text: Nome"></td>
<td data-bind="text: Descricao"></td>
</tr>
</tbody>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
&#13;
我认为这个问题与异步调用有关。
欢迎所有帮助。
谢谢大家