将JSON散列数组解析为jQuery标记输入

Parse JSON array of hashes into jQuery tokenInput

本文关键字:jQuery 输入 JSON 数组      更新时间:2023-09-26

我实现了jQuery令牌输入,用于标记目的,用户可以搜索标签或创建新标签,这要归功于railscasts ep#382&ep#258。数据来自作为标签控制器的索引动作的tags.jsonurl。tags.json中的数据如下所示:

[
  {
    "created_at":"2013-06-21T16:30:19Z",
    "explanation":"hitting the hosel of the club",
    "id":8,
    "name":"shank",
    "updated_at":"2013-06-21T16:30:19Z",
    "updated_by":"andy"
  },
  {
    "created_at":"2013-06-22T17:40:37Z",
    "explanation":"hitting the ground before the ball",
    "id":12,
    "name":"chunk",
    "updated_at":"2013-06-22T17:40:37Z",
    "updated_by":"andy"
  }
]

我的标签有一个名称和一个解释,所以我想把它们包括在结果列表中,比如令牌和结果格式化演示http://loopj.com/jquery-tokeninput/demo.html#formatting.

下面的代码(为简洁起见,省略了条目数量)来自jQuery tokenInputToken and Results Formatting演示。

与其在这里手动输入"name":"Shank"以及其他省略的条目,我如何从tags.json哈希中提取名称和解释,并将其用于与结果格式化程序行相同的行中,例如item.name&item.解释?

tags.js

jQuery(function() {
var question = $('#question_tag_tokens')
  return question.tokenInput([{
       "name": "Shank",
       "explanation": "hitting the hosel of the club"
   }
 ], {
    propertyToSearch: ["name"],
    resultsFormatter: function(item){ return "<li>" + "<div class='tag' style='display:inline;color:#fff;'>" + item.name + "</div>" + " " + item.explanation + "</li>" },
    prePopulate: question.data('preload')
  });
});

您提到的示例的来源如下:

 $(document).ready(function() {
     $("#demo-input-local-custom-formatters").tokenInput(
         [{
             "first_name": "Arthur",
             "last_name": "Godfrey",
             "email": "arthur_godfrey@nccu.edu",
             "url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
         },
         {
             "first_name": "Adam",
             "last_name": "Johnson",
             "email": "wravo@yahoo.com",
             "url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png"
         },
         ...
         ], 
         {
             propertyToSearch: "first_name",
             resultsFormatter: function(item){ ... },
             tokenFormatter: function(item) { ... }
         });
});

tokenInput似乎采用了一组对象。使用ajax加载json后,只需将其传入并告诉它要搜索的字段以及一些用于格式化结果的回调。