2011-06-01 68 views
2

林使用jQuery UI自動完成功能。jQuery用戶界面自動完成:遠程源問題

當我使用一個局部變量源它的工作原理。

var json = [ 
      {type: "Utente",label: "Luca XXXX",url: "http://lvh.me:3000/users/4dde465add53e04e5c000001"}, 

      {type: "Domanda",label: "Luca asdas adsfdsfdsf sdsd",url: "http://lvh.me:3000/questions/luca-asdas-adsfdsfdsf-sdsd"}, 
    ]; 

但是,當我從另一個文件返回相同的來源,它不起作用。我在firebug中找到了JSON對象,看起來和我的本地變量json一樣。

的代碼如下:

$(".query-input").autocomplete({ 
     minLength: 3, 
     source: "/search.json", 
     select: function(event, ui) { window.location = ui.item.url } 
    }) 
    .data("autocomplete")._renderItem = function(ul, item) { 
     return $("<li></li>") 
      .data("item.autocomplete", item) 
      .append("<a href=" + item.url + ">"+ item.label +"</a><span>" + item.type + "</span>") 
      .appendTo(ul); 
    }; 

這是search.json.erb文件:

[<% @results.each do |r| %> 
<% if r.is_a? User %> 
    {type: "Utente",label: <%= r.name.to_json.html_safe %>,url: <%= user_url(r.id).to_json.html_safe %>}, 
<% elsif r.is_a? Question %> 
    {type: "Domanda",label: <%= r.text.to_json.html_safe %>,url: <%= question_url(r.slug).to_json.html_safe %>}, 
<% elsif r.is_a? Topic %> 
    {type: "Argomento",label: <%= r.name.to_json.html_safe %>,url: <%= topic_path(r.id).to_json.html_safe %>}, 
<% end %> 
<% end %>] 

有什麼不對?

回答

0

問題是錯過的回調。自動完成需要一個回調參數才能正常工作。 右search.json代碼如下:

<%= "#{params[ :callback ]}(" if params[:callback] -%> 
[<% @results.each_with_index do |r, i| %> 
    <% if r.is_a? User %> 
    { 
     type: "Utente", 
     label: <%= r.name.to_json.html_safe %>, 
     url: "<%= user_url(r.id) %>" 
    } 
    <% elsif r.is_a? Question %> 
    { 
     type: "Domanda", 
     label: <%= r.text.to_json.html_safe %>, 
     url: "<%= question_url(r.slug) %>" 
    } 
    <% elsif r.is_a? Topic %> 
    { 
     type: "Argomento", 
     label: <%= r.name.to_json.html_safe %>, 
     url: "<%= topic_path(r.slug) %>" 
    } 
    <% end %> 
    <%= "," unless i == @results.count - 1 %> 
<% end %>] 
<%= ")" if params[:callback] -%> 
0
$(".query-input").autocomplete({ 
      minLength: 3, 
      dataType: 'json', 
      source: "/search.json", 
      select: function(event, ui) { window.location = ui.item.url } 
}) 

您應該提到的dataType爲「json的」

+0

提及。它不起作用。 – tanzio 2011-06-01 09:28:11

0

我不認爲 html_safe將換用雙引號字符值。

編輯:原來html_safe加雙引號字符。然而,在你的Firebug跟蹤的JSON是無效的,不會在你的問題的代碼相匹配:

[ 
    { 
     type: "Utente", 
     label: "Luca XXXX", 
     url: "lvh.me:3000/users/4dde465add53e04e5c000001"; <-- syntax error 
    }, { 
     type: "Domanda", 
     label: "Luca asdas adsfdsfdsf sdsd", 
     url: "lvh.me:3000/questions/luca-asdas-adsfdsfdsf-sdsd"; <-- syntax error 
    }, 
] 

有不應該是url值後分號。

+0

不行。 html_safe用雙引號包裝值。 這是從螢火蟲響應的複製/粘貼: [ \t \t {類型: 「Utente」,標籤: 「盧卡XXXX」,URL: 「http://lvh.me:3000/users/4dde465add53e04e5c000001」}, \t \t {類型: 「Domanda」,標籤: 「盧卡asdas adsfdsfdsf sdsd」,URL: 「http://lvh.me:3000/questions/luca-asdas-adsfdsfdsf-sdsd」}, ] – tanzio 2011-06-01 10:07:07

相關問題