select2 - 将远程数据与多个选择和预数据相结合

时间:2013-05-30 01:18:37

标签: javascript jquery ajax jquery-select2

您好我希望使用选择2和我目前看到的它看起来不错。我试图做一件事。

我希望通过对json文件的ajax调用来获取我的数据 - 他们的网站上有一个关于如何执行此操作的示例,但我正在尝试使用预填充列表。

我的意思是当用户例如点击此链接上的电影搜索时

http://ivaynberg.github.io/select2/#infinite

列出了json文件中的前10部电影,因此有一些预选。

任何人都可以指出我正确的节奏

这是我到目前为止的代码

function movieFormatResult(movie) {
    var markup = "<table class='movie-result'><tr>";
    if (movie.posters !== undefined && movie.posters.thumbnail !== undefined) {
        markup += "<td class='movie-image'><img src='" + movie.posters.thumbnail + "'/></td>";
    }
    markup += "<td class='movie-info'><div class='movie-title'>" + movie.title + "</div>";
    if (movie.critics_consensus !== undefined) {
        markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>";
    }
    else if (movie.synopsis !== undefined) {
        markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>";
    }
    markup += "</td></tr></table>"
    return markup;
}

function movieFormatSelection(movie) {
    return movie.title;
}

$(document).ready(function() {
$("#e7").select2({
    placeholder: "More",
    minimumInputLength: 3,
    ajax: {
        url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
        dataType: 'jsonp',
        quietMillis: 100,
        data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page, // page number
                apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total; // whether or not there are more results available

            // notice we return the value of more so Select2 knows if more results can be loaded
            return {results: data.movies, more: more};
        }
    },
    formatResult: movieFormatResult, // omitted for brevity, see the source of this page
    formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    multiple: true,
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});
});

和html

    <article class="row" id="infinite">
<div class="span12">

   <p> 
 <input type="hidden" class="bigdrop" id="e7" style="width:200px"/> 



   </p>

</div>
</article>

1 个答案:

答案 0 :(得分:0)

您可以将minimumInputLength参数设置为0,然后尝试在没有搜索值的情况下查询您的网址。然后设置服务器响应,如果没有搜索字符串,则返回10个选项。