2013-06-23 45 views
0

我有用于标记目的的jQuery token输入,用户可以通过railscasts搜索标签或创建一个新标签ep#382 & ep#258。数据来自tags.json url,这是标签控制器的索引操作。从tags.json数据看起来像这样:将JSON数组解析为jQuery tokenInput

[ 
    { 
    "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 tokenInput 令牌和结果格式演示。

除了在这里手动输入“名称”:“Shank”以及其他省略的条目,我如何从tags.json散列中提取名称和解释并将它们与结果格式化程序行,例如item.name & item.explanation?

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') 
    }); 
}); 
+1

你问在JavaScript中如何从rails加载该json?这个例子显示你可以将整个数组传递给你的'tokenInput'调用。 –

+0

好吧,它比我想象的要简单得多,你可以通过令牌输入('tags.json')访问item.explanation,并在答案@joeshmo和生病的时候很乐意接受。 – dodgerogers747

回答

1

为您所提到的实施例中的源是这样的:

$(document).ready(function() { 
    $("#demo-input-local-custom-formatters").tokenInput(
     [{ 
      "first_name": "Arthur", 
      "last_name": "Godfrey", 
      "email": "[email protected]", 
      "url": "https://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png" 
     }, 
     { 
      "first_name": "Adam", 
      "last_name": "Johnson", 
      "email": "[email protected]", 
      "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,你只需将它传入并告诉它要搜索的字段和一些回调来格式化结果。