這是我第一次嘗試select2,我正在觸及一個可能是基本問題的問題。選擇2問題填充選擇
選擇控制代碼:
<select class="form-control" id="trade-select" name="trade-select">
<option>...</option>
</select>
我用下面的代碼通過一個ColdFusion函數來獲取數據:從調用返回到AJAX URL
var options =
{
theme: 'bootstrap',
ajax:
{
url: "/ajax/search-trades.cfm",
dataType: 'json',
data: function (params) { return { query: params.term, 'groups_only': true }; },
processResults: function (data, page)
{ // parse the results into the format expected by Select2.
alert(data.DATA); // see note further below
return {results: data.DATA, more: false};
}
}
};
$('#trade-select').css('width', '100%').select2(options)
.on('change', function(event)
{
if (this.value == '') return;
$('#trade-select').val('').trigger('change');
});
原始JSON數據如下:
{"COLUMNS":["TRADE_CATEGORY"],"DATA":[["Appliance Repairs"],["Furniture Repair"],["Painting & Decorating"]]}
上述代碼中的警報返回以下內容,essentinti結盟沒有括號或任何一個逗號分隔的列表:
電器售後維修,傢俱修理,噴漆&裝飾
的問題是,選擇不與返回的數據填充。我猜這是與返回數據的格式有關的東西。
不知道我是否提供了足夠的信息,所以讓我知道你是否需要其他東西。
對於任何可能有想法的ColdFusion開發人員,以下是通過ajax url調用的ColdFusion模板。我知道我可以直接撥打電話到CFC,而不需要中間模板:
<cfsilent>
<cfparam name="url.groups_only" default="true">
<cfparam name="url.query" default="">
<cfset oSystem = createObject("component","cfcs.system")>
<cfset qTradeCategories = oSystem.getTradeCategories(
groups_only=url.groups_only,
query=url.query)>
</cfsilent>
<cfoutput>#SerializeJSON(qTradeCategories)#</cfoutput>
(編輯)望着例子,選擇2預計該數據將在比你的CFM腳本返回不同的。 [這個例子](https://select2.github.io/examples.html)表明它需要一個類似''{id:0,text:'enhancement'}]''的結構數組。這不是你的CF腳本返回的。或者修改腳本以返回適當的結構,或者循環訪問processResults()中的'data'對象並構建select2期望的結構。 – Leigh
@Leigh,這正是我在答案中的例子:) – Dekel
好的,我會試一試,然後回來。我相信你是對的。 – user460114