将xml从php传递给javascript作为对象

时间:2013-12-04 20:01:56

标签: javascript php xml json object

我有一个描述网站菜单的xml:

<?xml version="1.0" encoding="UTF-8"?>
<menu>
        <item titulo="Início" tipo="conteudo" codigo="inicio" classe="btnMenu01" />
        <item titulo="O Sintran" tipo="submenu" codigo="osintran" classe="btnMenu01">
            <subitem titulo="Apresentação" tipo="pagina" codigo="apresentacao" classe="btnMenu02" />
            <subitem titulo="Editorial" tipo="lista" param="artigos,assunto,editorial" codigo="editorial" classe="btnMenu02" />
            <subitem titulo="Estatuto" tipo="arquivos" param="descricao,estatuto" codigo="estatuto" classe="btnMenu02" />
        </item>
        <item titulo="Notícias" tipo="conteudo" codigo="noticias" classe="btnMenu01" />
        etc...
    </menu>

只有两个级别,所以很简单。我通过这一行传递给JavaScript:

var SubMenus = <?php echo(json_encode($SubMenus)) ?>;

我可以通过以下方式枚举我需要的值:

for(i in SubMenus){
    console.log("Submenu "+i+"...");
    Atts = SubMenus[i]["@attributes"];
    for(j in Atts){
        console.log(" - "+j+": "+Atts[j]);
    }
}

问题是@attributes对JavaScript Object类型没有任何意义,我自己发现了这个属性。所以我不确定我是否正在使用正确的技术来完成任务,我可能会使用一种方法,当事情变得复杂时会崩溃......

你是如何完成这项任务的?或者你认为这样可以吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

Atts = SubMenus[i].attributes;
// did not work for user

更新:查看此post on converting xml to an object with javascript,它还会显示如何访问/打印出来