填充<选择>< /选择>与另一盒 [英] Populate a <select></select> box with another

查看:107
本文介绍了填充<选择>< /选择>与另一盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<select name="class">

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

</select>

<select name="subject">

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

</select>

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

now i want to use the ajax to populate the subject list box.. I have no idea how to do it.

推荐答案

您可以订阅第一选择框的变化事件,然后通过将选定值触发一个Ajax请求到服务器。然后,在此请求的成功回调,你可以使用由服务器返回的JSON数组来更新第二个选择框的内容。这里有一个如何实现这一目标使用jQuery的例子:

You could subscribe to the change event of the first select box and then trigger an ajax request to your server by passing the selected value. Then in the success callback of this request you could use the JSON array returned by the server to update the contents of the second select box. Here's an example of how to achieve this using 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从服务器返回的可能是这样的:

and the JSON returned from the server could look like this:

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

这篇关于填充&LT;选择&GT;&LT; /选择&GT;与另一盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆