Jquery类型错误on无法读取undefined的属性'length'

时间:2013-09-19 23:03:23

标签: javascript php jquery ajax json

我正在努力改变选择的下拉菜单。为此,我使用jquery,ajax和json。

function ChooseGroupScript() {

                    $.getJSON('edit_scripts.php', {group:$('#group').val()}, function(data) {
                        var select = $('#subject');
                        var options = select.attr('options');
                        $('option', select).remove();

                            $.each(data, function(index, array) {
                                options[options.length] = new Option(array['subject']);
                            });

                    });

                }

                $(document).ready(function() {
                        ChooseGroupScript();
                        $('#group').change(function() {
                                ChooseGroupScript();
                        });

                });

我检查了控制台:我收到这样的错误:

Jquery type error on cannot read property 'length' of undefined

这是我的PHP:

if(isset($_GET['group'])){
$currentscript = $clients->curr_group_content($_GET['group']);
$scriptscount = sizeof($currentscript);
      for($i=0;$i<$scriptscount;$i++){
        $subject = $currentscript[$i]['subject'];
      }
}
echo json_encode($subject);

HTML:

<form>

<select name="group" id="group">
    <option>comming from database.....</option>
</select>

<select name="subject" id="subject">
</select>
</form>

2 个答案:

答案 0 :(得分:0)

选项不是select元素的属性。您可能只是想直接向元素添加新选项:

       var select = $('#subject');
       // remove this: var options = select.attr('options');
       $('option', select).remove(); // or select.empty() to clean it out

       $.each(data, function(index, array) {
            select.append(new Option(array['subject']));
       });

答案 1 :(得分:0)

在您的代码中

var options = select.attr('options');

它不对,因为它不是属性。获得所有选择的正确方法

var options = $('#subject options');

loop你可以

var select = $('#subject').empty();
$.each(data, function(index, val) {
    select.append($('<option/>', { 'value':index, 'text':val }));
});

A similar answer with example is here.