Select2无法使用Ajax远程数据

时间:2018-07-07 03:34:31

标签: jquery ajax jquery-select2

我尝试按照http://select2.github.io/select2/的示例进行操作,以使我的基本select2 ajax远程数据正常运行。但是,它返回错误为

  

未捕获的错误:无select2 / compat / initSelection

我四处搜寻,发现了类似的问题select2 - initselection error,但模糊不清可以帮助解决当前的问题。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Select2 Ajax</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>
    <select class="js-data-example-ajax" name="state">

    </select>
    <script>
        $('.js-data-example-ajax').select2({
            placeholder: "Search for a repository",
            minimumInputLength: 1,
          ajax: {
            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
            // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
          },
          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); });
                }
            },

            escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
        });
    </script>
</body>
</html>

上面的代码有什么问题?我想知道它的哪一点对我来说是正确的,并且可以正常工作?谢谢。

0 个答案:

没有答案