尽管data-pre html标记具有预期值,但Jquery预填充数据仍返回null

时间:2014-04-03 16:23:17

标签: ruby-on-rails html5 jquery-tokeninput

我正在使用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:

enter image description here

正如您所看到的,在html中有一个具有正确值的数据属性,但我没有在预先填充的区域中看到它们。

在我的javascript中,我使用 console log 查看输出,它返回null,当我尝试在控制台中查询此ID时,我确实得到了所需的属性:

enter image description here

问题是 - 这段代码出了什么问题?

注意:我也尝试在jquery中为#token-input-citizen_profile_attributes_city更改ID。

修改 将包装和对象包装到数组后,预填充工作,但它预填充未定义:

enter image description here

enter image description here

  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 enter image description here

使用$ .parseJSON解析预填充没有帮助:

enter image description here

EDIT3

使用$ .parseJSON控制台日志 enter image description here

1 个答案:

答案 0 :(得分:0)

原始代码存在多个问题。

  1. 预填充必须始终使用JSON 数组,而不仅仅是最初使用的对象。

  2. 第二个问题是在data-pre属性中编码JSON的结果编码。 JSON必须是HTML编码的,即用"替换引号。

  3. 为了澄清,这就是data-pre属性在上面的情况下应该是什么样子,我的图像rails有一些自动html编码字符串的方法。

    data-pre="[{"id":2368,"name":"Tokajík"}]"
    

    Updated Fiddle显示完全正常的版本。请注意,我的错误是数据不需要像之前在评论中建议的那样进行JSON解析。希望这有帮助!