我有web应用程序,我正在尝试使用knockout.js填充我的html表,但我的表仍然是空的。我的数据是通过ajax调用的。 jQuery和Knockout.js都引用了我的页面。这是代码;
HTML
<table id="payment_schedule">
<thead>
<tr class="tableHeader">
<th width="50px">
Index
</th>
<th width="50px">
Due Date
</th>
</tr>
</thead>
<tbody>
<tr data-bind="foreach: paymentSchedules">
<td data-bind="text: Index"></td>
<td data-bind="text: Month"></td>
</tr>
</tbody>
</table>
JavaScript函数
function GetComputation() {
$.ajax({
url: '/UnitSearch/CalculateMortgage',
cache: false,
dataType: 'json',
success: function (data) {
viewModel.paymentSchedules(data.PaymentSchedules);
}
});
}
var data = [];
var viewModel = {
paymentSchedules: ko.observableArray(data)
};
ko.applyBindings(viewModel);
从ajax返回的数据
答案 0 :(得分:5)
您的代码应该可以正常运行。您尚未显示调用GetComputation
函数的位置,但这是一个完整的示例。
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
public class UnitSearchController : Controller
{
public ActionResult CalculateMortgage()
{
var data = new
{
PaymentSchedules = new[]
{
new { Index = "Reservation Fee", Month = "23-Jan-13" },
new { Index = "Reservation Fee", Month = "25-Jan-13" },
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
索引视图(~/Views/Home/Index.cshtml
):
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table id="payment_schedule">
<thead>
<tr class="tableHeader">
<th>Index</th>
<th>Due Date</th>
</tr>
</thead>
<tbody data-bind="foreach: paymentSchedules">
<tr>
<td data-bind="text: Index"></td>
<td data-bind="text: Month"></td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/knockout-2.1.0.js")"></script>
<script type="text/javascript">
var data = [];
var viewModel = {
paymentSchedules: ko.observableArray(data)
};
ko.applyBindings(viewModel);
function GetComputation() {
$.ajax({
url: '/UnitSearch/CalculateMortgage',
cache: false,
success: function (data) {
viewModel.paymentSchedules(data.PaymentSchedules);
}
});
}
// I am calling the GetComputation function immediately in this example
// to populate the table with data but you could call it whenever you want
GetComputation();
</script>
</body>
</html>
在此示例中,我立即调用GetComputation
,但您可以调整代码并随时调用它。另请注意,我已在data-bind="foreach: paymentSchedules"
而非<tbody>
元素上应用了<tr>
。
答案 1 :(得分:3)
未测试,但您可以尝试移动数据绑定
data-bind="foreach: paymentSchedules"
到tbody而不是tr?
foreach淘汰文档也是如此。请参阅http://knockoutjs.com/documentation/foreach-binding.html