2012-05-14 12 views
0

我如何使用每个循环来创建使用ajax从json文件返回的每个数据的手风琴容器?从foreach循环创建从json返回的数据的dijit accordian容器

我试过了!这是它的方式吗?

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

回答

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 
    }); 
}); 

这是HOWTO :) 在任何时候你可以使用商店并获取一些物品,可以说你想过滤出一些特定的物品,请致电.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-example and http://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore