使用jquery ajax请求解析xml

时间:2011-12-14 00:16:13

标签: jquery xml ajax parsing

我有这个xml文档:

<?xml version="1.0" encoding="utf-8"?>
<root>
<chapter>
<lesson>message 1</lesson> 
<lesson>message 2</lesson>
<lesson>message 3</lesson>
<lesson>message 4</lesson>
<lesson>message 5</lesson>
<lesson>message 6</lesson>
<lesson>message 7</lesson>
<lesson>message 8</lesson>
<lesson>message 9</lesson>
<lesson>message 10</lesson>
<lesson>message 11</lesson>
</chapter>
</root>

这是我的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>  
<script type="text/javascript" src="jquery.js"></script>  
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "numbers.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {

  $(xml).find("chapter").each(function()  {

      $(this).find("lesson").each(function()  {


         $("#dropdownlist").val($(this).text());

         $("select").change(function () {          
 var str = "";          
 $("select option:selected").each(function () {                
str += $(this).val().text() + " ";              
});         
$("#dropdownlist").val(str);        
})        
.change();

      });
      });
}



});
</script>  
</head>

<body>  
<div>
<form id="myform" name="form1" action="" method="get">
<input style="border-style: inset" maxlength="70" size="90" type="text" id="dropdownlist" />
</form>
</div>
<table>
<p style="font-family: 'Monotype Corsiva'" align="right">
    chapter
    <select style="width: 100px" name="lessons" id="dropdownlist">
        <option>lesson_1</option>
        <option>lesson_2</option>
        <option>lesson_3</option>
        <option>lesson_4</option>
        <option>lesson_5</option>
        <option>lesson_6</option>
        <option>lesson_7</option>
        <option>lesson_8</option>
        <option>lesson_9</option>
        <option>lesson_10</option>
        <option>lesson_11</option>
    </select>
</p>
</table>
</body>  
</html>  

我的问题是代码堆栈只显示xml解析的第一个结果。当我从下拉菜单中选择第一个选项时,一切正常,但是当我选择其他选项堆栈并再次向我显示时。有什么建议?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "numbers.xml",
        dataType: "xml",
        success: function(response) {
            $('lesson', response).each(function() {
                $("#dropdownlist").append($('<option />').text($(this).text()));
            });
        }
    });

    $("select").change(function() {
        var str = '';

        $(this).find(":selected").each(function() {
            str += $(this).text() +' ';
        });

        $("#dropdownlist").val(str);
    }).change();
});

每次循环时,您都会在元素中附加change()触发器。