使用jquery从xml动态加载数据到下拉框

时间:2009-03-17 17:50:03

标签: jquery

我接手了一个小型的网络应用程序。我正在学习JQuery,所以我想用JQuery重写当前的java脚本。这就是我所拥有的 1. xml文件如下

<courses>
    <course title="math">
        <time>1:00pm</time>
        <time>3:00pm</time>
    </course>
    <course title="physic">
        <time>1:00pm</time>
        <time>3:00pm</time>
    </course>
</courses>
  1. 我喜欢加载下拉框标题。
  2. 从box1中选择标题时,下拉框2将填写对标题的回复时间。
  3. 感谢您的任何提示和帮助。

1 个答案:

答案 0 :(得分:4)

这应该让你开始:

<script type="text/javascript">
$(document).ready(function() {
    var course_data; // variable to hold data in once it is loaded
    $.get('courses.xml', function(data) { // get the courses.xml file
        course_data = data; // save the data for future use
                            // so we don't have to call the file again
        var that = $('#courses'); // that = the courses select
        $('course', course_data).each(function() { // find courses in data
            // dynamically create a new option element
            // make its text the value of the "title" attribute in the XML
            // and append it to the courses select
            $('<option>').text($(this).attr('title')).appendTo(that);
        });
    }, 'xml'); // specify what format the request will return - XML

    $('#courses').change(function() { // bind a trigger to when the
                                      // courses select changes
        var val = $(this).val(); // hold the select's new value
        var that = $('#times').empty(); // empty the select of times
                                        // and hold a reference in 'that'
        $('course', course_data).filter(function() { // get all courses...
            return val == $(this).attr('title'); // find the one chosen
        }).find('time').each(function() { // find all the times...
            // create a new option, set its text to the time, append to
            // the times select
            $('<option>').text($(this).text()).appendTo(that);  
        });
    });
});
</script>

Courses:
<select id='courses'>
    <option value='0'>----------</option>
</select>
<br>
Times:
<select id='times'>
    <option value='0'>----------</option>
</select>

它在做什么:

我正在使用$(document).ready();等待页面准备就绪。一旦它,我将加载文件courses.xml中的所有数据(您将更改为返回XML文件的任何数据)。获得此数据后,我将使用XML中所有课程的值填充课程<select>。然后,每次更改课程<select>时,我都会触发一个触发器。当发生这种情况时,我会找到所选择的课程并循环遍历时间<select>

经过测试和工作。