javascript - Make correct json data format for select2
问题描述
i am trying to ajax remote data for select2(using 4.0.6-rc.1), tried a few examples, at first the q parameter was undefined but i solved it and now the select is not giving me the results,don't know how to format the json data tried the following and getting the following error in the console:
$('#compose_username').select2({
dropdownParent: $("#modal-compose"),
placeholder: "Search country here...",
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
// escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
if (repo.loading) return repo.text;
return repo.desc;
}
function formatRepoSelection(repo) {
return repo.desc || repo.text;
}
USERNAME.PHP
include('../core/config.php');
try {
$stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$json[] = ['id'=>$row['id'], 'username'=>$row['username']];
}
echo json_encode($json);
} catch(PDOException $e) {
echo $e->getMessage();
}
JSON DATA:
if i type a
then getting the following in console but no option is showing in select2
(3) [{…}, {…}, {…}]
0
:
{id: "1", username: "admin"}
1
:
{id: "29", username: "adil3310"}
2
:
{id: "30", username: "asdsad"}
length
:
3
__proto__
:
Array(0)
解决方案
经过一番努力,我设法让它工作,我试图解析 Json 数据并且它已经被解析的原因,所以我使用它并且它工作。下面的完整工作示例,可能对其他人有所帮助:
$('#compose_username').select2({
// SET THIS IF SELECT IS IN A MODAL
dropdownParent: $("#modal-compose") ,
placeholder: "Search country here...",
// MINIMUM INPUT TO SEARCH BEFORE
minimumInputLength: 3,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
$('#compose_username').val(null).trigger('change');
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, page) {
console.log(data);
var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
return { results: result };
}
}
});
PHP( FOR GETTING LIST OF USERNAME, 我们可以在查询中设置限制)
try{
$stmt = $db_con->query("SELECT id,username FROM users WHERE username LIKE '%".$_GET['q']."%' LIMIT 10");
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$json[] = ['id'=>$row['id'], 'username'=>$row['username']];
}
echo json_encode($json);
}
catch(PDOException $e){
echo $e->getMessage();
}
推荐阅读
- javascript - 单击其他位置时关闭侧边菜单
- javascript - 最快的字符串包含签入数组以获取 JS 中的大量数据
- python - Django - 模型元选项 app_label 不起作用
- sql - 为什么id序列主键不断变化?
- html - Flexbox 不会垂直居中父元素的子元素
- haskell - Haskell 中的 Lambda 抽象模式匹配
- javascript - 通过 axios 发送数据时 Multer req.files 未定义,但使用 Postman 时一切正常
- python-3.x - 如何获取 Javascript 生成的内容
- xml - 在 XQuery 中检查多个项目时返回一个真/假
- c - 我的堆排序项目的时间复杂度是 N * log(N) 吗?