2016-05-23 16 views
0

無法選擇新添加的selectize組件後Ajax調用無法選擇新添加的selectize組件後Ajax調用

我已經預先填入的選項與當前選擇的選項,並試圖獲取更多的選項來自服務器的ajax調用。 我的服務器返回這樣的數據,但我不知道該怎麼做與此數據

[{"id":303,"name":"Short Sleeve Opening"}] 

我使用addOption和refreshOptions方法試過,但他們似乎並沒有工作。 下面是調用selectize組件的一段代碼。

$(function() { 
    $select_options = $('select').selectize({ 
     plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'], 
     delimiter: ',', 
     persist: false, 
     create: function (input) { // I am not sure if this is of any use, as I never found the control to enter in this part of code during debugging. 
      return { 
       value: input, 
       text: input 
      } 
     }, 
     load: function (query, callback) { 
      if (!query.length) return callback(); 
      $.ajax({ 
       dataType: 'json', 
       url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query), 
       error: function() { 
        callback();  //Not sure what the callback should be, documenation is not self explanatory 
       }, 
       success: function (res) { 
       //Added this callback to add the new options to the list, it is adding the new options to the list but I can't select them at all 
       //Moreover, second time I try to use autocomplete it doesn't work. The control doesn't reach the load method, and no error observed in console 
        for (index in res) { 
         $('.selectize-dropdown-content').append('<div class="option" data-selectable="" data-value="' + res[index].id + ' ">' + res[index].name + '</div>'); 
        } 
       } 
      }); 
     } 
    }); 
}); 

將新選項永久添加到列表中的確切方法是什麼?

回答

0

終於實現這種浪費之後整整一天:

$(function() { 
    $select_options = $('select').selectize({ 
     plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'], 
     delimiter: ',', 
     persist: false, 
     options: [], 
     load: function (query) { 
      $.ajax({ 
       dataType: 'json', 
       url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query), 
       success: function (res) { 
        updateOptions(res); 
       } 
      }); 
     } 
    }); 
    var updateOptions = function (newOptions) { 
     var selectize = $select_options[0].selectize; 
     for (index in newOptions) { 
      selectize.addOption({ 
       value: newOptions[index].id, 
       text: newOptions[index].name, 
      }); 
     } 
     selectize.refreshOptions(); 
    } 
});