AJAX,从XML文件填充下拉菜单

时间:2013-11-07 19:59:25

标签: html ajax xml

我正在开展一个项目,我不知道接下来该做什么。我的目标是使用xml文件填充下拉菜单。菜单基于4个步骤。 “Fylke”“Kommune”“Kategori”“Dato”。现在我得到xml将数据提供给“Fylke”,示例如下。当用户从“Fylke”菜单中选择Akershus时,下一步是用Halden填充“Kommune”。

这是XML:

<arrangement>
   <fylke name="Akershus">
   <kommune name="Halden">
   <arrangement id="570215856">
   <kategori>Moro</kategori>
   <dato>2013-10-10</dato>
</arrangement>

这是脚本:(此时正在向菜单输入“fylke”。)

 $(document).ready( function() {
arrangementer();
 fetch();
 });

 /*function fetch() {

 setTimeout( function() {
    arrangementer();
    fetch();
   }, 100);

   }*/

   function arrangementer() {

   $.ajax({ 

    url: "arrangementer.xml",
    dataType: "xml",
    success: function(data) {

        $('ul').children().remove();

        $(data).find("arrangement fylke").each( function() {

            var info = '<a href="#">'+$(this).attr("name")+'</a>';

            $('ul').append(info);

        });

    },
    error: function() { $('ul').children().remove(); 
        $('ul').append("<li>There was an error!</li>"); }
}); 
}

2 个答案:

答案 0 :(得分:0)

你正在使用jquery吗?

如果需要,您需要将click事件附加到外部ul,这可以在ready函数

中完成
$( "ul li" ).click(function() {
  alert( "Handler for .click() called." );
});

http://api.jquery.com/click/

您目前没有将li项目添加到您的ul jQuery: how to add <li> in an existing <ul>?

您确实需要为要更新的元素提供ID,以便您可以使用

$(" #myid li ").append(info);

否则,您将向表单http://api.jquery.com/id-selector/

上的所有ul元素添加信息

答案 1 :(得分:0)

不确定我的问题是否正确,但希望这会有所帮助:

$(xml).find("arrangement fylke").each( function(i) {
    var info = '<a href="#" nodeno="'+i+'" >'+$(this).attr("name")+'</a>'; //attribute nodeno added, carries the number of the node you will need later
    $('ul').append(info); 
});

$('ul').on("click", function(e){ //when clicked on one of those elements
    var nodeno = $(e.target).attr("nodeno"); //get nodeno attribute from clicked object
    $(xml)[nodeno].find("arrangement kommune").each( function(i){ //get the node by id and...
        var info = '<a href="#" nodeno="'+i+'" >'+$(this).attr("name")+'</a>';
        $('#menuitem2').append(info); //...populate your submenu with the kommune object
    } );
});

编辑:一点解释

这将导致fylke链接,如:

<a href="#" nodeno="0">Fylke 1</a>
<a href="#" nodeno="1">Fylke 2</a>

当单击其中一个时,您只需从单击的元素中读取nodeno属性,然后使用该属性从xml中获取相应的节点。那么你只使用那个节点的kommune来填充下一个菜单级别。

希望我的问题得到解决,这有助于

相关问题