我想從AJAX JSON條目更新KnockoutJS viewmodel。我不確定如何做到這一點。將Ajax JSON POST方法綁定到KnockoutJS Viewmodel
這裏是我的代碼:
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function() {
self.Currencies.push({
CurrencyFrom: "",
CurrencyTo: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
//Need to Get method to Bind To CurrencyModel;
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
$(document).ready(function() {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
這裏是從服務器獲取的JSON數據:
{
"d": [
{
"__type": "Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM",
"CurrencyFrom": "ZAR",
"CurrencyTo": "USD"
},
{
"__type": "Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM",
"CurrencyFrom": "USD",
"CurrencyTo": "ZAR"
}
]
}
HTML:
<table class="table table-striped">
<thead>
<tr>
<th>
Currency From
</th>
<th>
Currency To
</th>
</tr>
</thead>
<tbody data-bind="foreach: Currencies">
<tr>
<td data-bind="text: CurrencyFrom">
</td>
<td data-bind="text: CurrencyTo">
</td>
</tr>
</tbody>
</table>
視圖模型是非常簡單的,我有一個貨幣從,和貨幣到我想要添加和從表中刪除。