我試圖使用Select2和來自服務器的JSON數據創建一個下拉列表。我試圖按照他們的例子,它的工作原理,但我很難完成它。使用Select2從服務器檢索JSON
我使用下面的代碼從數據庫中的數據,我可以打印到控制檯,但我不能得到的數據顯示爲一個下拉
$(".js-example-basic-single").select2({
ajax: {
url: "DBHandler.php?k=",
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params.term);
return {
search: params.term // search term
};
},
processResults: function (data, params) {
// 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, except to indicate that infinite
// scrolling can be used
console.log(data)
params.page = params.page || 1;
return {
results: data.items
//pagination: {
//more: (params.page * 30) < data.total_count
//}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 3
});
我的HTML :
<select class="js-example-basic-single form-control" multiple="multiple">
</select>
我的PHP:
$stmt = $this->con->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode(array_unique($results));
的console.log(數據)輸出:
Zuber, W. P., Mrs.,Zoellner String Quartet,Zeta Chi,YWCA,Yonge, H. M.,YMCA Friendship Council,YMCA,Yellow Fever,yearbooks,Yarbrough, Reed, Mrs.,Yancey, William L.,Yale University,Yale,Wynne, W. W.,Wynne, Andrew Jackson "Jack",writing,Wright, T. P. (Thomas Parks),Wright, Homer,Wright, G. H.,Wright & Co.,wrestling,Worms Orchestra,World War I,World War 1,World Series,World Fellowship Campaign,Wooten, B. A. (Benjamin Allen),Woodmen's Circle,Woodmen of the World,Woodall, A. M. (Aaron Montgomery),Wood, Leonard, 1860-1927,Wood, Clement, 1888-1950,Wood, C. P.,wood,women,Woman's Missionary Society,Wolcott, Edward Oliver, 1848-1905,Wofford College,Wisconsin,Wirt Society student organizations,Wirt Society,Wirt Literary Society,Winston, Margaret,Winston, E. T.,Windham,
所以我的問題是我如何獲得data.items來填充<select></select>
標籤?
做你試圖循環'data.items'做沿線'$ .append'東西,你的'select'下拉? –
我累了。讓我再嘗試一次。 – Sedrick
我的第一個評論是錯誤的,我在文檔中看到,如果你從'select2'使用ajax而不是這行'result:data.items,'應該爲你呈現結果,你可以粘貼你的json數據,請摘錄 –