我已经从file_put_contents
创建了文件faqs.json并得到了正确的结果(见图1)。但是,当我尝试使用“ Select2 JS”进行渲染时,它总是以“无法加载结果”结尾,我只是按照网站上的给定说明进行操作。我无法理解的一件事是如何从json文件中提取post_title
和post_name
。我相信我在这里缺少什么。
注意:json文件内容是从wordpress的“自定义帖子类型”中获取的
这是我的示例json文件。 图1
[
{
"ID": 1336,
"post_title": "test",
"post_status": "publish",
"post_name": "test",
"post_excerpt": ""
}
{
"ID": 1335,
"post_title": "What are the requirements for",
"post_status": "publish",
"post_name": "what-are-the-requirements-for",
"post_excerpt": ""
}
]
这是我的JavaScript文件。 图2
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div class="col-sm-1">' +
'<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
'</div>' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.full_name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
'</div>';
if (repo.description) {
markup += '<div>' + repo.description + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.full_name || repo.text;
}
$(document).ready(function(){
$(".js-data-example-ajax").select2({
ajax: {
url: $json + "faqs.json",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// 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
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});