2013-05-30 104 views
8

嗨我期待使用select 2和我目前看到的它看起來不錯。我盡力做一件事。select2 - 結合獲取遠程數據與多選和預數據

我正在尋找讓我的數據與ajax調用json文件 - 有一個在他們的網站上如何做到這一點的例子,但我想有一個預填充列表。

我的意思是,當例如用戶點擊搜索電影這個鏈接

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

第10部電影在JSON文件中列出所以有一些prechoices上。

任何人都可以點我在正確的dieection

這裏是我到目前爲止的代碼

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> 

回答

0

您可以將minimumInputLength參數設置爲0,這將然後嘗試查詢沒有搜索值的網址。然後設置您的服務器響應,如果沒有搜索字符串,則返回10個選項。