好吧,我确定这里有一些简单的设置错误,但我不是 100% 是什么。
所以我正在尝试使用 Select2 AJAX 方法作为用户搜索数据库并选择结果的一种方式。通话本身会返回结果,但它不允许我从列表中选择答案。它似乎也不允许您在悬停或向上/向下箭头时“选择”它。所以不用多说,这是我的代码:
index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="select2/select2.css" media="screen" />
<script src="select2/select2.js"></script>
<script src="select.js"></script>
</head>
<body>
<input type="text" style="width: 500px" class="select2">
</body>
</html>
选择.js
jQuery(function() {
var formatSelection = function(bond) {
console.log(bond)
return bond.name
}
var formatResult = function(bond) {
return '<div class="select2-user-result">' + bond.name + '</div>'
}
var initSelection = function(elem, cb) {
console.log(elem)
return elem
}
$('.select2').select2({
placeholder: "Policy Name",
minimumInputLength: 3,
multiple: false,
quietMillis: 100,
ajax: {
url: "http://localhost:3000/search",
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
search: term,
page: page || 1
}
},
results: function(bond, page) {
return {results: bond.results, more: (bond.results && bond.results.length == 10 ? true: false)}
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: initSelection
})
})
JSON 响应
{
error: null,
results: [
{
name: 'Some Name',
_id: 'Some Id'
},
{
name: 'Some Name',
_id: 'Some Id'
}
]
}
似乎一切都正确,但我无法真正选择答案并将其输入框中。我的代码哪里有问题吗?
最佳答案
看了another answer之后似乎我还需要在每次调用时传递 id 字段,否则它将禁用输入。
修复它的示例代码:
$('.select2').select2({
placeholder: "Policy Name",
minimumInputLength: 3,
multiple: false,
quietMillis: 100,
id: function(bond){ return bond._id; },
ajax: {
url: "http://localhost:3000/search",
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
search: term,
page: page || 1
}
},
results: function(bond, page) {
return {results: bond.results, more: (bond.results && bond.results.length == 10 ? true: false)}
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: initSelection
})
编辑
由于这个问题一直受到好评,我会详细说明一下。 .select2() 方法需要一个唯一的 id
所有结果的字段。值得庆幸的是,有一个解决方法。 id
选项接受这样的函数:
function( <INDIVIDUAL_RESULT> ) {
// Expects you to return a unique identifier.
// Ideally this should be from the results of the $.ajax() call.
}
因为我的唯一标识符是 <RESULT>._id
,我只是return <RESULT>._id;
关于javascript - Select2 Ajax 方法不选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14819865/