【发布时间】:2014-04-03 16:23:16
【问题描述】:
我正在使用 Jquery token input plugin 进行自动完成和 prepopulating data.
自动完成看起来不错,但我在预填充数据方面确实存在一些问题。
这是我的javascript:
tokenOptions = {
theme: 'facebook',
searchingText: null,
hintText: null,
noResultsText: null,
allowFreeTagging: true,
tokenValue: 'name',
searchDelay: 1000,
prePopulate: $('#citizen_profile_attributes_city').data('pre')
}
$(document).ready ->
console.log('prepopulate:' + tokenOptions.prePopulate)
$("#citizen_profile_attributes_city").tokenInput("/cities.json",
tokenOptions )
这是表单的一部分(在 HAML 中):
= f.text_field :city, :data => { 'pre' => @profile.pre_populate_city } , :id => 'citizen_profile_attributes_city'
这是 pre_populate_city 方法:
def pre_populate_city
city_name = self.city
city_id = (City.find_by_name city_name).id
{ "id" => city_id, "name" => city_name}.to_json
end
这是返回的html:
如您所见,在 html 中有一个具有正确值的数据属性,但我在预填充区域中看不到它们。
在我的 javascript 中,我使用 console log 查看输出,它返回 null,当我尝试在控制台中查询此 id 时,我确实得到了所需的属性:
问题是 - 这段代码有什么问题?
注意:我也尝试在 jquery 中将 id 更改为 #token-input-citizen_profile_attributes_city。
编辑 将对象包装成数组后,预填充工作,但它预填充未定义:
def pre_populate_city
city_name = self.city
city_id = (City.find_by_name city_name).id
[{ "id" => city_id, "name" => city_name}.to_json]
end
EDIT2
使用 $.parseJSON 解析预填充没有帮助:
EDIT3
带有 $.parseJSON 的控制台日志
【问题讨论】:
标签: ruby-on-rails html jquery-tokeninput