2013-06-23 46 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,你只需將它傳入並告訴它要搜索的字段和一些回調來格式化結果。