Сделать запрс к серверу в jQuery select2

254
15 июня 2018, 09:20

Я хотел бы узнать, как отправляются запросы к серверу используя jQuery, select2 и ajax, а также как полученный ответ помещается в выпадающий список в select2.

Answer 1

Вот здесь вы можете найти пример кода выполняющий запрос к серверу для получения данных.

    $("#e6").select2({ 
        placeholder: "Search for a repository", 
        minimumInputLength: 1, 
        ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
            url: "https://api.github.com/search/repositories", 
            dataType: 'json', 
            quietMillis: 250, 
            data: function (term, page) { 
                return { 
                    q: term, // search term 
                }; 
            }, 
            results: function (data, page) { // parse the results into the format expected by Select2. 
                // since we are using custom formatting functions we do not need to alter the remote JSON data 
                return { results: data.items }; 
            }, 
            cache: true 
        }, 
        initSelection: function(element, callback) { 
            // the input tag has a value attribute preloaded that points to a preselected repository's id 
            // this function resolves that id attribute to an object that select2 can render 
            // using its formatResult renderer - that way the repository name is shown preselected 
            var id = $(element).val(); 
            if (id !== "") { 
                $.ajax("https://api.github.com/repositories/" + id, { 
                    dataType: "json" 
                }).done(function(data) { callback(data); }); 
            } 
        }, 
        formatResult: repoFormatResult, // omitted for brevity, see the source of this page 
        formatSelection: repoFormatSelection,  // omitted for brevity, see the source of this page 
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller 
        escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results 
    }); 
     
       function repoFormatResult(repo) { 
      var markup = '<div class="row-fluid">' + 
         '<div class="span2"><img src="' + repo.owner.avatar_url + '" /></div>' + 
         '<div class="span10">' + 
            '<div class="row-fluid">' + 
               '<div class="span6">' + repo.full_name + '</div>' + 
               '<div class="span3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' + 
               '<div class="span3"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' + 
            '</div>'; 
 
      if (repo.description) { 
         markup += '<div>' + repo.description + '</div>'; 
      } 
 
      markup += '</div></div>'; 
 
      return markup; 
   } 
 
   function repoFormatSelection(repo) { 
      return repo.full_name; 
   }

READ ALSO
Отобразить ошибку при валидации формы

Отобразить ошибку при валидации формы

код который делает блок с ошибками

237
Как определить ориентацию экрана Unity?

Как определить ориентацию экрана Unity?

Есть два Canvas с разными видами расширениями кнопок "Portrait" и "Landscape" нужно определить в какой ориентации девайс и включить соответствующее меню

254
Google API (Таблицы)

Google API (Таблицы)

Пытаюсь к приложению прикрепить прайс, который находится на Гугл дискеНачал пробовать подключать API

304