我正在使用select2 jquery gem.我正在尝试获取与用户输入内容相匹配的主题列表.它没有按预期工作,我花了一整天时间试图找出原因.我一直在控制台中收到此错误 Uncaught TypeError: Cannot call
Uncaught TypeError: Cannot call method 'toUpperCase' of undefined select2.js?body=1:363 Uncaught TypeError: Cannot call method 'localeCompare' of undefined
第二个错误链接到此行上的js文件
return this.text.localeCompare(term) === 0;
有什么我做错了吗?
提前致谢.
我的路线:
get '/topic/topic_list' => 'topic#topic_list'
在我的Topic控制器中,我有:
def topic_list
@topics = Topic.order(:name)
respond_to do |format|
format.html
format.json { render json: @topics.where('name like ?', "%#{params[:q]}%") }
end
end
主题js文件
$(function () {
$('#story_topic_list').select2({
tags: true,
width: '100%',
tokenSeparators: [","," "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
multiple: true,
maximumSelectionSize: 5,
formatSelectionTooBig: function (limit) {
return 'You can only add 5 topics'
},
ajax: {
dataType: 'json',
url: '/topic/topic_list.json',
data: function (term, page) {
return { q: term };
},
results: function(data, page) {
return { results: data };
}
}
})
});
以我的形式,我有
<%= f.label :topic_list %> <%= f.text_field :topic_list %>
另外/topic/topic_list.json返回:
[{"id":2,"name":"app","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.615+00:00","updated_at":"2014-03-23T20:12:24.615+00:00","count":1},{"id":5,"name":"app tech website","added_by":1,"cover_id":null,"created_at":"2014-03-23T20:23:33.754+00:00","updated_at":"2014-03-23T20:23:33.754+00:00","count":1},{"id":3,"name":"tech","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.668+00:00","updated_at":"2014-03-23T20:12:24.668+00:00","count":1},{"id":4,"name":"website","added_by":null,"cover_id":null,"created_at":"2014-03-23T20:12:24.677+00:00","updated_at":"2014-03-23T20:12:24.677+00:00","count":1}]
select2不知道您要从传回的数据中使用哪个字段.假设它是名称字段,请单独添加此功能(不在select2中):
function format(item) { return item.name; }
以及以下两个选项2:
formatSelection: format, formatResult: format
