使用json返回的数据从foreach循环创建dijit accordian容器

时间:2012-05-14 02:00:14

标签: json dojo

如何使用a为每个循环为使用ajax从json文件返回的每个数据创建折叠容器?

我试过这个!这是通往它的方式吗?

dojo.xhrGet({
    url:"json/"file_Name".json",
    handleAs: "json",
    timeout: 10000,
    load: function(response,details){
        container(response)},
    error: function(error_msg,details){
        container(error_msg, details);
    }

    });

         //how do i use the json file to add data to the array arrFruit and then create dijit accordian container for every data in the array//
    container = function(array, domConstruct) {

      var arrFruit = ["apples", "kiwis", "pineapples"];
      array.forEach(arrFruit, function(item, i){
            domConstruct.create("li", {innerHTML: i+1+". "+item}, "properties");
      });



    };
     //the response data from my json file is:-
     [
{
    "itemId": 1234,
    "Name": "Name",
            }]

1 个答案:

答案 0 :(得分:0)

我建议你重新编写它以利用ItemFileReadStore。商店是一个数据容器,您可以通过其ID来提取商品。这意味着您需要稍微更改您的json,其中包含标识符的描述以及 - 如果有的话 - 这是子属性键。

JSON:

{
  identifier: 'itemId',
  // you dont seem to have child references any but these are defaults
  childrenAttrs: ['items', 'children'],
  items: [
    {
     itemId: 1234,
     name: 'Name'
    }, {
       ...
    }
  ]
}

然后在你的代码中,而不是使用.xhr在这样的商店中使用.fetch:

// 1.7+ syntax, pulling in dependencies. 
// We want accordion and some other display widget like contentpane.
// Also we await domReady before calling our function
require(["dojo/data/ItemFileReadStore", "dijit/layout/AccordionContainer", "dijit/layout/ContentPane", "dojo/domReady!"], function(itemStore, accordion, contenpane) {

  // this section is called when loading of itemstore dependencies are done
  // create store
  var store = new itemStore({
    url:"json/"file_Name".json"
  });
  // create container
  var acc = new accordion({style:"height: 300px"}, 'someDomNodeId');

  // call XHR via .fetch and assign onComplete (opposed to 'load') callback
  store.fetch({ onComplete: function(items) {

    // items is an array of all the objects kept in jsonObject.items array
    items.forEach(function(item) {
       acc.addChild(new contentpane({
          title: "Name for id: " + store.getValue(item, 'itemId'),
          content: store.getValue(item, 'name')
       }));
    });
  console.log(acc.getChildren()); // << would print out an array of contentpane widgets
  });
});

这是怎么做:) 在任何给定的时间你可以使用商店并获取一些项目,假设你想要过滤掉一些特定的项目,请调用.query如下:store.fetch({query: { name: '*foo'/*all item.name ending with foo*/ }, onComplete: function(items) { /*cb func*/});

请参阅 http://livedocs.dojotoolkit.org/dijit/layout/AccordionContainer#programmatic-examplehttp://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore