从ajax字符串设置select2的初始值

时间:2017-01-20 22:24:19

标签: jquery ajax jquery-select2 select2 jquery-select2-4

我正在使用select2 v.4.0.3

我的表单上有两个字段,一旦显示,就会调用ajax来填充表单数据。

当进行ajax调用并成功时,我想根据“left_options”和“right_options”中的值填充select2框,这是我数据库中包含这样的整数字符串的两个字段:25,0或3,41,4

 //get all the record info and fillfields if in update mode
 $.ajax({
 url: "ajax_quick_get_value.php",
 type: "get",
 data: {
     table: 'invoice_hearing_aids',
     field: 'id',
     field_equals: $('#modal_form_invoice_hearingaids #hearing_aids_id').val()
 },
 dataType: 'json',
 success: function (response) {
//response here if data response

if (response) {

 //loop through the data and fill form fields based on id's
    $.each(response, function (index, value) {
        if(index != 'left_options' || index != 'right_options') {
            $('#modal_form_invoice_hearingaids #hearing_aids_' + index).val(value);
        }

        if(index == 'left_options') {
            var left_current_string = value;

            //will throw an error if it's null, so check first
            if (left_current_string != null) {
                var left_array = new Array();
                var left_array = left_current_string.split(',');

                $('#modal_form_invoice_hearingaids #hearing_aids_left_options').select2('val', left_array);
            }

        }

        if(index == 'right_options') {
            var right_current_string = value;

            //will throw an error if it's null, so check first
            if (right_current_string != null) {
                var right_array = new Array();
                var right_array = right_current_string.split(',');

                $('#modal_form_invoice_hearingaids #hearing_aids_right_options').select2('val', right_array);
            }
        }

    });

我能够确认从我的ajax调用返回的JSON数据是否包含以逗号分隔的left_options和right_options的值。

只有选项字符串中的第一个值被填充到select2框中。之后的其他所有内容都没有填充。

 $('#modal_form_invoice_hearingaids #hearing_aids_left_options').select2('val', left_array)

我认为问题出在上面的代码中? right_options代码也是一样的。

我觉得这样有效,但由于某种原因突然停了下来。我用的是Chrome。

以下是我如何动态填充我的select2选项(只在这里显示right_options):

 <div class="form-group">
                <label class="control-label"></label>
                <select id="hearing_aids_right_options"  name="right_options[]" class="form-control hearing_aid_options" multiple style="width: 100%">
                <?php 
if($company->find_hearing_aid_options()) { 
$options = $company->hearing_aid_options(); 
foreach ($options as $option) { 
    echo '<option value="' .  $option->id . '">' .  $option->name . '</option>';
     };
};
 ?>
 </select>

我不确定是否需要提供更多代码,但我可以。感谢。

2 个答案:

答案 0 :(得分:0)

您需要在服务器端以正确的方式构造数据,以便在名为key:value的数组中返回items[]对的数组。此外,select2对于在ajax请求成功中处理数据有自己的想法,因此您应该使用库实现,例如:

$('select').select2({
     ajax: {
        url: "ajax_quick_get_value.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 30) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 1,
      templateResult: formatItems, 
      templateSelection: formatItemSelection
    });
});

现在你唯一需要担心的是2个函数formatItemsformatItemSelection

您可以为这些实现简单的操作,例如:

function formatItems(item) {
    return item.name;
}

function formatItemSelection (item) {
    return item.name;
}

就是这样。现在你只需要确保在服务器端正确返回它,使其成为如上所述的正确JSON响应:

return json_encode([
    'items' => $myItemsArray
]);

然后你只需要返回一个至少具有id属性和name属性的对象数组。

答案 1 :(得分:0)

通过将代码更改为:

,这对我有用
 $('#modal_form_invoice_hearingaids #hearing_aids_left_options').val(left_array).trigger("change");
相关问题