0

如何使用 for each 循环为使用 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",
            }]
4

1 回答 1

0

我建议您将其重写为利用 ItemFileReadStore。Store 是一个数据容器,您可以在其中通过 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-examplehttp://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore

于 2012-05-18T11:12:28.157 回答