ajax下的嵌套顺序列表 [英] nested order list under ajax

查看:66
本文介绍了ajax下的嵌套顺序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个来自两个不同xml文件的数组,一个存储分类信息,一个存储分类下的产品。他们通过categoryID连接。下面是xml文件的示例。我阅读这些XML文件并使用ajax保存数据。

  categories.xml 
< Categories>
< CategoryID> 1< / CategoryID>
< CategoryName>饮料< / CategoryName>
<说明>软饮料,咖啡,茶,啤酒和麦酒< /说明>
< / Categories>
<类别>
< CategoryID> 2< / CategoryID>
< CategoryName>调味品< / CategoryName>
<描述>甜味和咸味调味料,滋味,涂抹和调味料< /说明>
< / Categories>



products.xml
<产品>
< ProductID> 1< / ProductID>
< ProductName> Chai< / ProductName>
< CategoryID> 1< / CategoryID>
< QuantityPerUnit> 10盒x 20袋< / QuantityPerUnit>
< UnitPrice> 18< / UnitPrice>
< / Products>
<产品>
< ProductID> 2< / ProductID>
< ProductName> Chang< / ProductName>
< CategoryID> 1< / CategoryID>
< QuantityPerUnit> 24 - 12盎司瓶子< / QuantityPerUnit>
< UnitPrice> 19< / UnitPrice>
< / Products>

我读取了两个文件,如下所示:

 $'$'
$'$'$ $ b $'$'$'$'成功:function(data){
$(data).find('CategoriesRoot Categories')。each(function(i){
cateid = $(this).find('CategoryID').text ();
catename = $(this).find('CategoryName')。text();
catedescription = $(this).find('Description')。text();
categoryarray [i] = new Array();
categoryarray [i] [0] = cateid;
categoryarray [i] [1] = catename;
categoryarray [i] [2] = catedescription;
});
$ .ajax({
类型:'GET',
url:'products.xml',
dataType:xml ,
success:function(data){
$(data).find('ProductsRoot Products')。each(function(j){
proid = $(this).find('ProductID')。text();
proname = $(this).find('ProductName')。text();
catid = $(this).find('CategoryID')。text();
quantity = $(this).find('QuantityPerUnit')。text();
price = $(this).find('UnitPrice')。text();
productarray [j] = new Array();
productarray [j] [0] = proid;
productarray [j] [1] =代名词;
productarray [j] [2] = catid;
productarray [j] [3] =数量;
productarray [j] [4] = price;

});

我需要显示下面的嵌套顺序列表

  i.food 
a)产品
b)另一种产品
ii。喝
a)可乐
b)果汁

为此,我有循环在ajax里面

  for(var k = 0; k< categoryarray.length; k ++){
if(categoryarray ('。cate ol')。append('< li id =Cate_'+ k +'>'+ categoryarray [k] [1] + '< /立GT;');
for(var l = 0; l< productarray.length; l ++){
if(categoryarray [k] [0] == productarray [l] [2]){
$( '#Cate_'+ k).append('< ol id =Pro_'+ l +'type =a>< / ol>');
$('#Pro_'+ l).append(< li>+ productarray [l] [1] +< / li>);
}
}
}
}

但它会显示第一个类别,然后用这样的重复和随机顺序填充它下面的所有产品和其他类别。最后,其他七个类别的订单列为ii-viii。

  i.Beverages(1st cate)
a.Chai(第一类美食)
b.Condiments(第二类)
.Aniseed Syrup(第二类美食)
b.Confections(第三类美食亲)根据它))
c。乳制品(第四类(根据它没有亲))
d.Grains /谷物(第五类)
a.hamburger面包(第五类美食)
b。肉类/家禽(第六类)
a.beef汉堡(第六类美食)
b.Produce(第七类)
c.海鲜(第八类)
a.tiger大虾(第八类美食)
b.cooked大虾(第八类美食)
a.chicken汉堡(第七类美食)
b.Produce(7th cate)
c.Seafood(8th cate)
.....

任何人都可以帮我弄清楚我做错了什么地方吗?
P.S.我只在这里放了一部分代码。如果您对我的要求感到困惑,请随时问我!
非常感谢!!!!

解决方案

创建一个数据结构可以帮助您更轻松地构建列表。



假设您有以下数据:

categories.xml

 <?xml version =1.0encoding =UTF-8?> 
<类别>
<类别>
< ID> 1< / ID>
<名称>饮料< /名称>
<说明>软饮料,咖啡,茶,啤酒和麦酒< /说明>
< / Category>
<类别>
< ID> 2< / ID>
<名称>调味品< /名称>
<描述>甜味和咸味调味料,滋味,涂抹和调味料< /说明>
< / Category>
< / Categories>

products.xml

 <?xml version =1.0encoding =UTF-8?> 
<产品>
<产品>
< ID> 1< / ID>
<名称> Chai< /名称>
< CategoryID> 1< / CategoryID>
< QuantityPerUnit> 10盒x 20袋< / QuantityPerUnit>
< UnitPrice> 18< / UnitPrice>
< / Product>
<产品>
< ID> 2< / ID>
<名称>常< /名称>
< CategoryID> 1< / CategoryID>
< QuantityPerUnit> 24 - 12盎司瓶子< / QuantityPerUnit>
< UnitPrice> 19< / UnitPrice>
< / Product>
<产品>
< ID> 3< ID>
<名称>陈< /名称>
< CategoryID> 2< / CategoryID>
< QuantityPerUnit> 6 - 20盎司瓶子< / QuantityPerUnit>
< UnitPrice> 5< / UnitPrice>
< / Product>
<产品>
< ID> 4< / ID>
<名称> Chow< /名称>
< CategoryID> 2< / CategoryID>
< QuantityPerUnit> 12 - 40盎司芥末< / QuantityPerUnit>
< UnitPrice> 14< / UnitPrice>
< / Product>
< / Products>

让我们构建一个对象,其中键是类别ID,值是类别数据字段产品来保存所有相关产品。

  {
'1':{
name:'Beverages',
description: '软饮料,咖啡,茶,啤酒和麦酒',
产品:
},
'2':{
名称:'调味品',
描述:'甜味和咸味调味料,滋味,涂抹和调味',
产品:[...]
}
}

$ b

  var data = {} ; 

categories.find('Category')。each(function(){
var category = $(this);
var id = category.find('ID') .text();
data [id] = {
id:id,
name:category.find('Name')。text(),
description:category。 find('Description').text(),
products:[]
};
})

products.find('Product')。each function(){
var product = $(this);
var categoryId = product.find('CategoryID')。text();
if(data.hasOwnProperty(categoryId)){
data [categoryId] .products.push({
id:product.find('ID')。text(),
name:product.find('Name')。text( ),
quantityPerUnit:product.find('QuantityPerUnit')。text(),
unitPrice:product.find('UnitPrice')。text()
});
}
});

一旦我们有了这个对象,我们现在可以通过运行两个嵌套循环来构建HTML。

  var list ='< ol type =i>'; 
$ .each(data,function(i,category){
list + ='< li>'+ category.name
list + ='< ol type =a >';
$ .each(category.products,function(j,product){
list + ='< li>'+ product.name +'< / li>';
});
list + ='< / ol>';
list + ='< / li>;
})
list + =' < /醇>';

把所有东西放在一起

 <! - 占位符保存列表 - > 
< div id =products>< / div>

< script>
$(函数(){
//获得2个ajax响应的简化方法
$ .when(
$ .get('categories.xml'),
$ .get('products.xml')
).done(function(catRes,prodRes){
var categories = $($。parseXML(catRes [2] .responseText))。find(' ('Products');

//构建一个数据结构来组织两个响应
var data = {};

categories.find('Category')。each(function(){
var category = $(this);
var id = category.find('ID')。text();
data [id] = {
id:id,
name:category.find('Name')。text ),
description:category.find('Description')。text(),
products:[]
};
})

产品.find('Product')。each(function(){
var product = $(this);
var categoryId = product.find('CategoryID')。text();
if(data.hasOwnProperty(categoryId)){
data [categoryId] .products.push({
id:product.find('ID')。text(),
name:product.find('Name')。text(),
quantityPerUnit:product.find('QuantityPerUnit')。text(),
unitPrice:product.find('UnitPrice')。 text()
});
}
});

//使用数据结构构建HTML
var list ='< ol type =i>';
$ .each(data,function(i,category){
list + ='< li>'+ category.name
list + ='< ol type =a >';
$ .each(category.products,function(j,product){
list + ='< li>'+ product.name +'< / li>';
});
list + ='< / ol>';
list + ='< / li>;
})
list + =' < /醇>';

$('#products')。html(list);
});
});
< / script>

有用的链接:




I have two arrays from two different xml files, one stores category information, one stores products under categories. They are connected via categoryID. Samples of the xml files are below. I read these xml files and save the data using ajax.

 categories.xml
    <Categories>
        <CategoryID>1</CategoryID>
        <CategoryName>Beverages</CategoryName>
        <Description>Soft drinks, coffees, teas, beer, and ale</Description>
    </Categories>
    <Categories>
        <CategoryID>2</CategoryID>
        <CategoryName>Condiments</CategoryName>
        <Description>Sweet and savory sauces, relishes, spreads, and seasonings</Description>
    </Categories>



products.xml
    <Products>
        <ProductID>1</ProductID>
        <ProductName>Chai</ProductName>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>
        <UnitPrice>18</UnitPrice>
    </Products>
    <Products>
        <ProductID>2</ProductID>
        <ProductName>Chang</ProductName>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
        <UnitPrice>19</UnitPrice>
    </Products>

I read two files like below

$.ajax({
    type: 'GET',
    url: 'categories.xml',
    dataType: "xml",
    success: function(data) {
        $(data).find('CategoriesRoot Categories').each(function(i){
            cateid = $(this).find('CategoryID').text();
            catename = $(this).find('CategoryName').text();
            catedescription = $(this).find('Description').text();
            categoryarray[i] = new Array();
            categoryarray[i][0] = cateid;
            categoryarray[i][1] = catename;
            categoryarray[i][2] = catedescription;
        });
        $.ajax({
            type: 'GET',
            url: 'products.xml',
            dataType: "xml",
            success: function(data) {
                $(data).find('ProductsRoot Products').each(function(j){
                    proid = $(this).find('ProductID').text();
                    proname = $(this).find('ProductName').text();
                    catid = $(this).find('CategoryID').text();
                    quantity = $(this).find('QuantityPerUnit').text();
                    price = $(this).find('UnitPrice').text();
                    productarray[j] = new Array();
                    productarray[j][0] = proid;
                    productarray[j][1] = proname;
                    productarray[j][2] = catid;
                    productarray[j][3] = quantity;
                    productarray[j][4] = price;

                });

And I need to show nested order list like below

i.food 
  a) product
  b) another product
ii. drink
  a) coke
  b) juice

To do that, I have the loop inside ajax below

for(var k=0;k<categoryarray.length;k++){
  if(categoryarray[k][0]!==""){
    $('.cate ol').append('<li id="Cate_' + k + '">'+categoryarray[k][1]+'</li>');
      for(var l=0;l<productarray.length;l++){
        if(categoryarray[k][0]==productarray[l][2]){
          $('#Cate_' + k).append('<ol id="Pro_' + l + '" type="a"></ol>');
          $('#Pro_' + l).append("<li>"+productarray[l][1]+"</li>");
        }
      } 
    }
  }     

But it shows the first category and then fills all the products and other categories under it with a repeated and random order like this. At the end, the other seven categories are listed with order as ii-viii.

i.Beverages(1st cate)
  a.Chai(1 pro of 1st cate)
  b.Condiments(2nd cate)
    a.Aniseed Syrup(1st pro of 2nd cate)
    b.Confections(3rd cate(no pro under it))
    c.Dairy Products(4th cate(no pro under it))
    d.Grains/Cereals(5th cate)
      a.hamburger bun(1st pro of 5th cate)
      b.Meat/Poultry(6th cate)
        a.beef burger(1st pro of 6th cate)
        b.Produce(7th cate)
        c.Seafood(8th cate)
          a.tiger prawns(1st pro of 8th cate)
          b.cooked prawns(2nd pro of 8th cate)
        a.chicken burger(2nd pro of 7th cate)
        b.Produce(7th cate)
        c.Seafood(8th cate)
         .....

Can anyone help me figure out where I did wrong? P.S. I put only a part of codes here. If you are confused about what I am asking, feel free to ask me! Many thanks!!!!

解决方案

Create a data structure that will help you build the list easier.

Suppose you have the following data:

categories.xml

<?xml version="1.0" encoding="UTF-8"?>
<Categories>
    <Category>
        <ID>1</ID>
        <Name>Beverages</Name>
        <Description>Soft drinks, coffees, teas, beer, and ale</Description>
    </Category>
    <Category>
        <ID>2</ID>
        <Name>Condiments</Name>
        <Description>Sweet and savory sauces, relishes, spreads, and seasonings</Description>
    </Category>
</Categories>

products.xml

<?xml version="1.0" encoding="UTF-8"?>
<Products>
    <Product>
        <ID>1</ID>
        <Name>Chai</Name>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>
        <UnitPrice>18</UnitPrice>
    </Product>
    <Product>
        <ID>2</ID>
        <Name>Chang</Name>
        <CategoryID>1</CategoryID>
        <QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
        <UnitPrice>19</UnitPrice>
    </Product>
    <Product>
        <ID>3</ID>
        <Name>Chen</Name>
        <CategoryID>2</CategoryID>
        <QuantityPerUnit>6 - 20 oz bottles</QuantityPerUnit>
        <UnitPrice>5</UnitPrice>
    </Product>
    <Product>
        <ID>4</ID>
        <Name>Chow</Name>
        <CategoryID>2</CategoryID>
        <QuantityPerUnit>12 - 40 oz mustard</QuantityPerUnit>
        <UnitPrice>14</UnitPrice>
    </Product>
</Products>

Let's build an object where the key is the category ID and the value is the category data with an additional field products to hold all its related products.

{
    '1': {
        name: 'Beverages',
        description: 'Soft drinks, coffees, teas, beer, and ale',
        products: [ ... ]
    },
    '2': {
        name: 'Condiments',
        description: 'Sweet and savory sauces, relishes, spreads, and seasonings',
        products: [ ... ]
    }
}

When building the object, the key is important because when we will be iterating over the products, we'll be able to easily add them to their respective category's products array as shown below:

var data = {};

categories.find('Category').each(function () {
    var category = $(this);
    var id = category.find('ID').text();
    data[id] = {
        id: id,
        name: category.find('Name').text(),
        description: category.find('Description').text(),
        products: []
    };
})

products.find('Product').each(function () {
    var product = $(this);
    var categoryId = product.find('CategoryID').text();
    if (data.hasOwnProperty(categoryId)) {
        data[categoryId].products.push({
            id: product.find('ID').text(),
            name: product.find('Name').text(),
            quantityPerUnit: product.find('QuantityPerUnit').text(),
            unitPrice: product.find('UnitPrice').text()
        });
    }
});

Once we have this object, we can now build the HTML by running two nested loops.

var list  = '<ol type="i">';
$.each(data, function (i, category) {
    list += '<li>' + category.name
    list += '<ol type="a">';
    $.each(category.products, function (j, product) {
        list += '<li>' + product.name + '</li>';
    });
    list += '</ol>';
    list += '</li>';
})
list += '</ol>';

Putting everything together

<!-- placeholder to hold list -->
<div id="products"></div>

<script>
$(function () {
    // simplified way to get 2 ajax responses
    $.when(
        $.get('categories.xml'),
        $.get('products.xml')
    ).done(function (catRes, prodRes) {
        var categories = $($.parseXML(catRes[2].responseText)).find('Categories'),
            products = $($.parseXML(prodRes[2].responseText)).find('Products');

        // build a data structure to organize both responses
        var data = {};

        categories.find('Category').each(function () {
            var category = $(this);
            var id = category.find('ID').text();
            data[id] = {
                id: id,
                name: category.find('Name').text(),
                description: category.find('Description').text(),
                products: []
            };
        })

        products.find('Product').each(function () {
            var product = $(this);
            var categoryId = product.find('CategoryID').text();
            if (data.hasOwnProperty(categoryId)) {
                data[categoryId].products.push({
                    id: product.find('ID').text(),
                    name: product.find('Name').text(),
                    quantityPerUnit: product.find('QuantityPerUnit').text(),
                    unitPrice: product.find('UnitPrice').text()
                });
            }
        });

        // build HTML using data structure
        var list  = '<ol type="i">';
        $.each(data, function (i, category) {
            list += '<li>' + category.name
            list += '<ol type="a">';
            $.each(category.products, function (j, product) {
                list += '<li>' + product.name + '</li>';
            });
            list += '</ol>';
            list += '</li>';
        })
        list += '</ol>';

        $('#products').html(list);
    });
});
</script>

Useful links:

这篇关于ajax下的嵌套顺序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆