将第三方JSON数据绑定到现有Viewmodel [英] Bind 3rd Party JSON data to Existing Viewmodel

查看:131
本文介绍了将第三方JSON数据绑定到现有Viewmodel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙着为我的网络应用创建货币模块,我正在使用Yahoo Finance API来返回我在本地数据库中定义的2种货币的货币转换率。我从API中获得了很好的JSON数据,我只是想将从财务API收到的JSON数据绑定到我现有的Viewmodel,以便我可以使用它。



这是我的代码:



  var  currency = < span class =code-keyword> function (data){
var self = this ;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(); // 我希望绑定从YAHOO FINANCE API(parseExchangeRate函数)返回的价格
}

var CurrencyModel = 功能(货币){
var self = this ;
self.Currencies = ko.observableArray(货币);

self.AddCurrency = function (){
self.Currencies.push({
CurrencyFrom:
CurrencyTo: < span class =code-string>

ConversionRate:
});
};

self.RemoveCurrency = function (货币){
self.Currencies.remove(货币);
};

self.Save = function (表格){
alert( 现在可以保存: + ko.utils.stringifyJson(self.Currencies));
};

$ .ajax({
url: CurrencyConfiguration.aspx / GetConfiguredCurrencies
// 当前页面,方法
数据:< span class =code-string>' {}'
// 参数map为JSON
类型: POST
// 数据必须张贴
contentType: application / json; charset = utf-8
// 发布JSON内容
dataType: JSON
// 数据类型是JSON(必须是大写的!)
超时: 10000
// AJAX超时
成功: function (结果){
var MappedCurrencies =
$ .map(Result.d,
function (item){
getRate(item.CurrencyFrom,item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);

},
错误:功能(xhr,status){
alert(status + - + xhr.responseText);
}
});
};

// 来自Yahoo Finance API的第三方JSON结果
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 +从+到+ %253DX%26F%3Dl1n '%20于是%20columns%3D'rate%2Cname' 和;格式= JSON&安培;回调= parseExchangeRate);
document .body.appendChild(script);
}

// 这是从JSON获得率的主要功能
function parseExchangeRate(YahooData){
var rate = YahooData。 query.results.row.rate;
// 我想将这个价格与我的观点模型绑定
}

$( document )。ready( function (){
var VM = new CurrencyModel();
ko.applyBindings(VM);
$(' [rel = tooltip]')。tooltip();
})



从我的应用程序返回我的JSON数据:

 {d:[{ __type: Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM, CurrencyFrom: ZAR, CurrencyTo: 美元, 速度:空},{ __类型:金融.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM,CurrencyFrom:USD,CurrencyTo:ZAR,Rate:null}]} 



从parseExchangeRate函数返回的JSON(Yahoo查询结果):

 parseExchangeRate({query:{count:1,created:2013-01-18T06:46:41Z, lang:en-US,results:{row:{rate:0.1129,name:ZAR to USD}}}}}; 

解决方案

.ajax({
url: CurrencyConfiguration.aspx / GetConfiguredCurrencies
// 当前页面,方法
数据:' {}'
// 参数图为JSON
类型: < span class =code-string> POST,
// 数据必须是已发布
contentType: application / json; charset = utf-8
// 发布JSON内容
dataType: JSON
// 数据类型是JSON(必须是大写!)
超时: 10000
// AJAX超时
成功: function (Result){
var MappedCurrencies =


.map( Result.d,
function (item){
getRate(item.CurrencyFrom,item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);

},
错误:功能(xhr,status){
alert(status + - + xhr.responseText);
}
});
};

// 来自Yahoo Finance API的第三方JSON结果
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 +从+到+ %253DX%26F%3Dl1n '%20于是%20columns%3D'rate%2Cname' 和;格式= JSON&安培;回调= parseExchangeRate);
document .body.appendChild(script);
}

// 这是从JSON获得率的主要功能
function parseExchangeRate(YahooData){
var rate = YahooData。 query.results.row.rate;
// 我想将这个比率与我的视图模型绑定
}


document )。ready( function (){
var VM = new CurrencyModel();
ko.applyBindings(VM);

I am busy creating a currency Module for my web app, I am using Yahoo Finance API to return the currency conversion rate of 2 currencies that I have defined in my local DB. I get the JSON data fine from the API, I just want to Bind the JSON data that I have received from the Finance API to my existing Viewmodel so that I can use it.

Here is my code:

var currency = function (data) {
           var self = this;
           self.CurrencyFrom = ko.observable(data.CurrencyFrom);
           self.CurrencyTo = ko.observable(data.CurrencyTo);
           self.ConversionRate = ko.observable(); // I WANT TO BIND MY RATE THAT IS RETURNED FROM YAHOO FINANCE API (parseExchangeRate Function) HERE
       }

       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) {
              getRate(item.CurrencyFrom, item.CurrencyTo);
              return new currency(item);
          }
          );
                   self.Currencies(MappedCurrencies);

               },
               error: function (xhr, status) {
                   alert(status + " - " + xhr.responseText);
               }
           });
       };

       //3rd Party JSON result from Yahoo Finance API
       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);
       }

        //THIS IS THE PRIMARY FUNCTION TO GET RATE FROM JSON
       function parseExchangeRate(YahooData) {
           var rate = YahooData.query.results.row.rate;
           //I WANT TO BIND THIS RATE TO MY VIEW MODEL
       }

       $(document).ready(function () {
           var VM = new CurrencyModel();
           ko.applyBindings(VM);
           $('[rel=tooltip]').tooltip();
       })


My JSON Data Returned from my App:

{"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}]}


The JSON returned from parseExchangeRate Function (Yahoo Query Result):

parseExchangeRate({"query":{"count":1,"created":"2013-01-18T06:46:41Z","lang":"en-US","results":{"row":{"rate":"0.1129","name":"ZAR to USD"}}}});

解决方案

.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) { getRate(item.CurrencyFrom, item.CurrencyTo); return new currency(item); } ); self.Currencies(MappedCurrencies); }, error: function (xhr, status) { alert(status + " - " + xhr.responseText); } }); }; //3rd Party JSON result from Yahoo Finance API 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); } //THIS IS THE PRIMARY FUNCTION TO GET RATE FROM JSON function parseExchangeRate(YahooData) { var rate = YahooData.query.results.row.rate; //I WANT TO BIND THIS RATE TO MY VIEW MODEL }


(document).ready(function () { var VM = new CurrencyModel(); ko.applyBindings(VM);


这篇关于将第三方JSON数据绑定到现有Viewmodel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆