我需要加载一个大型JSON文件,以成为 selectize.js 输入字段的菜单选项。在下面的工作示例中,直到用户首次在框中键入内容时才会进行AJAX调用。感谢您在页面开头加载JSON文件的帮助。
countries.json
[{"name":""}, {"name":"Afghanistan"}, {"name":"Belgium"}, {"name":"China"},{"name":"Denmark"}, {"name":"Estonia"}, {"name":"Finland"}, {"name":"Greece"}]
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>selectize</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/js/standalone/selectize.js"></script>
</head>
<body>
<label for="countries">Selectize</label>
<select class="form-control pickerSelectClass" id="countries"></select>
<script>
$('#countries').selectize({
valueField: 'name',
valueField: 'name',
labelField: 'name',
maxItems: 3,
options: [],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'countries.json',
type: 'GET',
dataType: 'json',
data: { country: query, },
error: function() { callback(); },
success: function(res) { callback(res); }
});
}
});
</script>
</body>
</html>
答案 0 :(得分:1)
IRC频道中的善良灵魂指向了这个解决方案,这似乎很有效:
$.ajax({
url: 'countries.json',
type: 'GET',
dataType: 'json',
data: { json: JSON.stringify(countries) },
error: function(err) { console.log(err); },
success: function(options) {
$('#countries').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
maxItems: 3,
preload: true,
options: options,
create: true,
});
}
});