用另一个填充<select> </select>框

时间:2011-09-03 09:28:56

标签: html ajax

<select name="class">

  <option>  --select class--  </option>

</select>

<select name="subject">

  <option> --select subject-- </option>

</select>

现在我想使用ajax来填充主题列表框..我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以订阅第一个选择框的更改事件,然后通过传递选定的值来触发对服务器的ajax请求。然后,在此请求的成功回调中,您可以使用服务器返回的JSON数组来更新第二个选择框的内容。以下是如何使用jQuery实现此目的的示例:

$(function() {
    $('.class').change(function() {
        // when the value of the first select changes trigger an ajax request
        var value = $(this).val();
        $.getJSON('/script.cgi', { selectedValue: value }, function(result) {
            // assuming the server returned json update the contents of the 
            // second selectbox
            var subject = $('.subject');
            subject.empty();
            $.each(result, function(index, item) {
                result.append(
                    $('<option/>', {
                        value: item.value
                        text: item.text
                    })
                );
            });
        });
    });
});

并且从服务器返回的JSON可能如下所示:

[ { value: '1', text: 'subject 1' }, { value: '2', text: 'subject 2' } ]