2012-09-12 50 views
6

我是新來的Javascript,jQuery,Ajax和jSON世界。Select2載入遠程數據與佔位符下拉

我需要做的是混合可用選擇2 2個選項

佔位符

$("#e2_2").select2({ 
    placeholder: "Select a State" 
}); 

加載遠程數據

$("#e6").select2({ 
    placeholder: "Search for a movie", 
    minimumInputLength: 1, 
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
     url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", 
     dataType: 'jsonp', 
     data: function (term, page) { 
      return { 
       q: term, // search term 
       page_limit: 10, 
       apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working 
      }; 
     }, 
     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 remote JSON data 
      return { 
       results: data.movies 
      }; 
     } 
    }, 
    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 
}); 

你可以從看選擇網站,這些選項是完全不同的。 當我點擊加載遠程數據字段時,它會打開一個搜索選項。但我不想那樣。我希望下拉列表中的選項可用於PlaceHolder示例。

在佔位符示例中,下拉列表中的可用選項在HTML中被硬編碼。 我需要的是,當你打開時,它會轉到json文件並返回json上可用的信息。

理想的做法是使用佔位符Select2的UI與裝載遠程日期的功能(在服務器上獲取json)形成另一個Select2示例。

有什麼想法?如果2不能合併,我可以使用任何超級快速的Ajax解決方案。

+0

它可能是值得看看的銳遠:http://angular-ui.github.com/#directives-select2 – Tosh

回答

1

如果你只需要通過AJAX將數據加載到您選擇2(通過遠程API無需搜索),你可以這樣來做:

$.get("/path/to/your/data.json", function(data){window.ajaxData=data;}); 
$("#e2_2").select2({data: window.ajaxData, placeholder: "Select a State"}); 

(使用全局變量往往是不好的做法,但它只是一個例子)