Ajax 在多个选择中附加选项

Ajax 在多个选择中附加选项,ajax,jquery-select2,Ajax,Jquery Select2,我想在multiple select中附加选项,选项值来自ajax responce 我将jquery-select2用于多个select字段 我的脚本代码 $.ajax({ type: "POST", data: {'tc_agency_code': agencycode,'tc_agency_name': agencyname,'tc_agency_address':address,'tc_contact_no':con

我想在multiple select中附加选项,选项值来自ajax responce 我将jquery-select2用于多个select字段 我的脚本代码

$.ajax({    
                type: "POST",
                data: {'tc_agency_code': agencycode,'tc_agency_name': agencyname,'tc_agency_address':address,'tc_contact_no':contactno,'tc_port_id':port,'tc_port_id':port,'tc_agency_description':description,'xhttp_call':'Y'},
                url: "<?php echo $this->baseurl(); ?>/agency/add",
                success:function(response){
                alert(response);
                    if(response =='null') {
                        error ='Agency name are already exist.';                
                        $( "#agency_name_error" ).html( error );
                        return false;
                    }

                    var result = $.parseJSON(response);
                    alert(result.tc_agency_id); //this alert showing id like '190'
                    alert(result.tc_agency_name); // this alert showing text like 'test'

                    $('#tc_agency_ids').append($('<option></option>').attr('value', "'"+ result.tc_agency_id +"'").text("'"+ result.tc_agency_name +"'"));

                    /* $('#tc_agency_ids').append($('<option>', { // i searched that this commented code is also correct for append the value in multiple select but not working in my code
                        value: result.tc_agency_id,
                        text : result.tc_agency_name 
                    })); */

                    $('#tc_agency_ids option[value='+ result.tc_agency_id +']').attr('selected', true);
                $.fancybox.close();

                },
                error:function (xhr, ajaxOptions, thrownError){
                        alert(thrownError); 
                    }
                });

您的代码很接近,但有一些更改:

不要用引号括住值和文本值。 将添加到Select2控件后,调用.change以更新该控件。 最好使用.prop而不是.attr来设置所选属性。 代码:


注意:我不认为您为.append显示的注释代码是正确的。你有看到这个的链接吗?

我用这个代码解决了这个问题, 警报发出后, 应使用附加推送代替附加推送

var data = $('#tc_agency_ids').select2('data');
                    data.push({id:result.tc_agency_id,text:result.tc_agency_name});
                    $('#tc_agency_ids').select2("data", data, true);

感谢所有

在将数据推送到选择字段后,我面临验证问题,jquery要求验证验证字段,当我删除验证时,post中显示的空数据,我认为出现此问题是因为数据未附加到列表中。任何人都有解决此问题的方法。谢谢,它的工作和这段代码也解决了我的验证问题,在我的回答评论
var data = $('#tc_agency_ids').select2('data');
                    data.push({id:result.tc_agency_id,text:result.tc_agency_name});
                    $('#tc_agency_ids').select2("data", data, true);