这让我困惑不解。一定是我没看到的小东西。我正在尝试使用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刷新?
发布于 2012-03-16 12:54:35
这没有理由不能很好地工作。如下所示。
http://jsfiddle.net/madcapnmckay/EYueU/
我将检查ajax post是否真的返回json数据,该json是否是一个数组,以及它是否被正确解析。
我必须调整ajax调用以使fiddle ajax处理程序正常工作。
我想不出更多了。
希望这能有所帮助。
发布于 2013-03-06 14:02:51
var self=this;
//var self first line in model
$.ajax({
url: ",
dataType: "json",
contentType: 'application/json',
type: "POST",
data: JSON.stringify({ }),
processdata: true,
beforeSend: function () {
$.mobile.loading('show');
},
error: function (xhr, textStatus, errorThrown) {
alert('Sorry!');
},
success: function (data) {
$.mobile.loading('hide');
if (data.result!= '') {
self.vendors(data.result);
} else {
self.vendors({something});
}
}
});
使用self.vendors而不是此viewModel.vendors
发布于 2017-10-13 00:10:00
这是我在我的MVC .net应用程序中使用knockout和jquery所做的工作。
// Scripts/groItems.js
(function () {
var ViewModel = function () {
items = ko.observableArray(),
ItemName = ko.observable(),
Img = ko.observable(),
Qty = ko.observable()
}
$.getJSON('/Items2/AllItems', function (data) {
for (var i = 0; i < data.length; i++) {
self.items.push(data[i]);
}
});
var vm = new ViewModel();
$(function () {
ko.applyBindings(vm);
});
}());
@model IEnumerable<GroModel.Item>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<div data-bind="text: items().length"></div>
<table class="container table table-hover">
<thead>
<tr>
<th>Item name</th>
<th>img</th>
<th>qty</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: ItemName"></td>
<td data-bind="text: Img"></td>
<td data-bind="text: Qty"></td>
</tr>
</tbody>
</table>
@section Scripts {
<script src="~/Scripts/knockout-3.4.2.js"></script>
<script src="~/Scripts/groItems.js"></script>
}
以下是我在Items2Controller.cs上编写的部分代码
private GroContext db = new GroContext();
public JsonResult AllItems()
{
return Json(db.Items.ToList(), JsonRequestBehavior.AllowGet);
}
希望这能有所帮助。谢谢
https://stackoverflow.com/questions/9730496
复制相似问题