从Knockoutjs中的json字符串中读取嵌套数组

时间:2012-09-18 09:08:04

标签: knockout.js

我将面临一个问题,即读取包含嵌套数组的json字符串。

{
    "invoiceSet": {
        "lines": [
            {
                "line": "Business Partner had two or more interactions in the last 30 days",
                "togState": "true",
                "links": [
                    {
                        "linktxt": "Interaction History",
                        "linkid": "IRHIST"
                    }
                ]
            },
            {
                "line": "Open CRC Complaints Exist",
                "togState": "false",
                "links": [
                    {
                        "linktxt": "Interaction History",
                        "linkid": "IRHIST"
                    }
                ]
            },
            {
                "line": "Open Complaints Exist",
                "togState": "true",
                "links": [
                    {
                        "linktxt": "Interaction History",
                        "linkid": "IRHIST"
                    }
                ]
            },
            {
                "line": "Business Partner is a landlord",
                "togState": "false",
                "links": []
            },
            {
                "line": "Remotes Business Partner",
                "togState": "true",
                "links": [
                    {
                        "linktxt": "Interaction History",
                        "linkid": "IRHIST"
                    }
                ]
            },
            {
                "line": "Recent move has occurred in the last 60 days",
                "togState": "false",
                "links": []
            }
        ]
    }
}

我正在使用ajax调用来获取字符串中的这个json

var setJsonText = jQuery.ajax({ url: ajxUrl,
                                            cache: false,
                                            async: false,
                                            type:"POST",
                                            dataType: "html" }).responseText;
var sets = jQuery.parseJSON( setJsonText );

viewModel.invLines(sets.invoiceSet.lines)

我的viewmodel

var viewModel = {
           invLines: ko.observableArray([]),
};

HTML

<table width="100%" >
 <tbody data-bind="foreach: invLines" style="width:100%">
  <tr>
   <td data-bind="text: line"></td>
   <td>
    <ul data-bind="foreach:links">
     <li>
      <a><span  data-bind="text:linktxt"></span></a>
     </li>
    </ul>
 </tbody>
</table>

该行已正确打印,但在相应链接上出现问题。请让我知道我做错了什么。

谢谢, Anshul Kaistha

1 个答案:

答案 0 :(得分:0)

你的问题可能出在你的ajax电话中。为什么要将数据作为HTML获取然后将其转换为JSON?为什么不把数据作为JSON?

无论如何,这个jsFiddle演示了你的代码工作(减去ajax调用)所以你发布的所有绑定看起来都是有效的:

http://jsfiddle.net/unklefolk/g9Q9V/3/

希望这有助于解决您的问题。