我有一个现有的视图模型,其中列出了我想要转换率的货币代码。我利用 Yahoo Finance API 为我的货币获取 JSON 结果。
如何将此第 3 方 JSON 结果绑定到我现有的 ViewModel。
来自 Yahoo Finance API 的 JSON:
parseExchangeRate({"query":{"count":1,"created":"2013-01-17T07:37:18Z","lang":"en-US","results":{"row":{"rate":"8.7967","name":"USD to ZAR"}}}});
我的视图模型代码:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(getRate(data.CurrencyFrom, data.CurrencyTo));
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
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) {
var MappedCurrencies =
$.map(Result.d,
function (item) { return new currency(item); });
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result
function getRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=parseExchangeRate");
document.body.appendChild(script);
}
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
我的 HTML:
<table class="table table-striped">
<thead>
<tr>
<th>
Date Updated
</th>
<th>
Currency From
</th>
<th>
Currency To
</th>
<th>
Conversion Rate
</th>
<th />
</tr>
</thead>
<tbody data-bind="foreach: Currencies">
<tr>
<td>
<label class="label">Date</label>
</td>
<td>
<input data-bind="value: CurrencyFrom, uniqueName: true" />
</td>
<td>
<input data-bind="value: CurrencyTo, uniqueName: true" />
</td>
<td>
<input data-bind="value: ConversionRate, uniqueName: true" />
</td>
<td>
<a href='#' data-bind='click: $root.RemoveCurrency'>Delete</a>
</td>
</tr>
</tbody>
</table>
我的 JSON 返回:
{"d":[{"__type":"Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM","CurrencyFrom":"ZAR","CurrencyTo":"USD","Rate":null},{"__type":"Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM","CurrencyFrom":"USD","CurrencyTo":"ZAR","Rate":null}]}