使用knockout js将jl数据从url绑定到div

时间:2013-05-27 08:16:38

标签: javascript jquery knockout.js

我正在点击一个网址并获取json数据,这个数据我想绑定到不同的div 来自url的json数据样本是

[{"CompanyCode":"17023928","LastTradedPrice":"19,849.65","Symbol":"NSE"},{"CompanyCode":"17023929","LastTradedPrice":"6,021.25","Symbol":"NIFTY"}]  

在这里我有不同符号的数据,我有两个不同的div同名作为符号。我想将该数据绑定到div。
div格式是

<div id="nse" >
 <div id="companyCode"></div>
 <div id="TradePrice"></div>
</div>
<div id="nifty" >
  <div id="companyCode"></div>
  <div id="TradePrice"></div>
</div>  

对于nse我希望nse json绑定并且用于漂亮,漂亮的数据绑定

2 个答案:

答案 0 :(得分:1)

使用下一个构造

<!-- ko foreach: myData -->
<!-- ko if : $data.Symbol === "NSE" -->
<div id="nse" >
 <span>This is NSE</span>
 <div id="companyCode" data-bind="text : $data.CompanyCode"></div>
 <div id="TradePrice"  data-bind="text : $data.LastTradedPrice"></div>
</div>
<!-- /ko -->
<!-- ko if : $data.Symbol === "NIFTY" -->
<div id="nifty" >
 <span>This is NIFTY</span>
 <div id="companyCode" data-bind="text : $data.CompanyCode"></div>
 <div id="TradePrice"  data-bind="text : $data.LastTradedPrice"></div>
</div>
<!-- /ko -->
<!-- /ko -->  

JSFiddle DEMO

或者您可以使用knockout-swith-case插件

编辑:

$.getJSON(url, function (data) { 
   self.myData =ko.observableArray(data); 
})

你应该在ajax请求中将myData定义为viewModel的一部分,例如

self.myData =ko.observableArray(data);   
$.getJSON(url, function (data) { 
    self.myData(data); 
})

答案 1 :(得分:0)

试试这个..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Testing</title>
    <script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function() {
            var A = [{ "CompanyCode": "111", "LastTradedPrice": "11,1", "Symbol": "NSE" }, { "CompanyCode": "567", "LastTradedPrice": "8568", "Symbol": "NIFTY" }, { "CompanyCode": "gjgh78", "LastTradedPrice": "56856", "Symbol": "NSE" }, { "CompanyCode": "ghj65g", "LastTradedPrice": "56675", "Symbol": "NIFTY"}];
            $('#tblNSE,tblNIFTY').empty();
            $.each(A, function(key, value) {
                if (value.Symbol == 'NSE') {
                    $('#tblNSE').append('<tr><td>Company Code : </td><td>' + value.CompanyCode + '</td><td>Last Traded Price : </td><td>' + value.LastTradedPrice + '</tr>');
                } else {
                    $('#tblNIFTY').append('<tr><td>Company Code : </td><td>' + value.CompanyCode + '</td><td>Last Traded Price : </td><td>' + value.LastTradedPrice + '</tr>');
                }
            });
        });

    </script>
</head>
<body>
    <div id="nse">
        <label>
            NSE
        </label>
        <table id="tblNSE">
        </table>
    </div>
    <br />
    <div id="nifty">
        <label>
            NIFTY
        </label>
        <table id="tblNIFTY">
        </table>
    </div>
</body>
</html>