从 .ajax() 调用加载一个 Knockout.js observableArray() [英] loading a knockout.js observableArray() from .ajax() call
问题描述
这让我很困惑.它一定是我没有看到的小东西.我正在尝试使用 ajax 调用在淘汰赛中加载一个非常简单的 observableArray
.
This puzzles me. It must be something small I'm not seeing. I'm trying to load a very simple observableArray
in knockout with an ajax call.
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刷新?
Question: Why does the successful ajax call, who's data
variable value matches byte-for-byte the hard typed value, not trigger the html refresh?
推荐答案
没有理由这行不通.正如这表明的那样.
There is no reason this would not work fine. As this demonstrates.
http://jsfiddle.net/madcapnmckay/EYueU/
我会检查 ajax 帖子是否实际返回了 json 数据,并且该 json 是一个数组并且它被正确解析.
I would check that the ajax post is actually returning json data and that that json is an array and that it's being parsed correctly.
我必须调整 ajax 调用才能让 fiddle ajax 处理程序正常工作.
I had to tweak the ajax call to get the fiddle ajax handlers to work correctly.
我想不出更多了.
希望这会有所帮助.
这篇关于从 .ajax() 调用加载一个 Knockout.js observableArray()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!