这让我很困惑。这一定是我没看到的小事。我正在尝试使用 ajax 调用在 knockout 中加载一个非常简单的 observableArray
。
javascript
// we bind the array to the view model property with an empty array.
var data = [];
var viewModel = {
vendors: ko.observableArray(data)
};
ko.applyBindings(viewModel);
$(function () {
// on this click event, we popular the observable array
$('#load').click(function () {
// WORKS. Html is updated appropriately.
viewModel.vendors([{ "Id": "01" },{ "Id": "02" },{ "Id": "03" }]);
// DOES NOT WORK. Fiddler2 shows the same exact json string come back
// as in the example above, and the success function is being called.
$.ajax({
url: '/vendors/10',
dataType: 'json',
success: function (data) {
viewModel.vendors(data);
}
});
});
});
html
<button id="load">Load</button>
<ul data-bind="template: { foreach: vendors }">
<li><span data-bind="text: Id"></span></li>
</ul>
<小时/>
问题:为什么成功的ajax调用(其data
变量值与硬类型值逐字节匹配)不会触发html刷新?
最佳答案
没有理由这不能正常工作。正如这表明的那样。
http://jsfiddle.net/madcapnmckay/EYueU/
我会检查 ajax post 实际上是否返回 json 数据,并且该 json 是一个数组并且它正在被正确解析。
我必须调整 ajax 调用才能使 fiddle ajax 处理程序正常工作。
我想不到更多了。
希望这有帮助。
关于javascript - 从.ajax()调用加载knockout.js observableArray(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9730496/