2011-12-14 28 views
1

我想修改這個jQuery UI的示例來接受2維JSON數據。 http://jqueryui.com/demos/autocomplete/#remote-with-cachejQuery UI自動完成 - 在'source'中使用多維數組值,緩存示例

var cache = {}, lastXhr; 
    $("#birds").autocomplete({ 
     minLength: 2, 
     source: function(request, response) { 
      var term = request.term; 
      if (term in cache) { 
       response(cache[ term ]); 
       return; 
      } 

      lastXhr = $.getJSON("search.php", request, function(data, status, xhr) { 
       cache[ term ] = data; 
       if (xhr === lastXhr) { 
        response(data); 
       } 
      }); 
     } 
    }); 

我將如何修改此用 '名' 值在JSON數據是這樣的:

[{"name":"TEST1","slug":"blah-blah"},{"name":"TEST","slug":"example-slug-here"}] 

回答

5

的自動完成構件的格式如下預計數據:

本地數據可以是簡單的字符串數組,也可以包含 陣列中每個項目的對象,其中標籤 財產或兩者。標籤屬性顯示在建議 菜單中。在用戶 從菜單中選擇了某些內容後,該值將被插入到輸入元素中。如果只指定了一個屬性, 將同時用於

(重點煤礦)

這並不意味着你不能使用不與響應遠程源格式;在調用所提供的response功能之前,您可以按摩數據以符合這些要求。記住

就這樣,我會修改例如,對於您的情況如下:

lastXhr = $.getJSON("search.php", request, function(data, status, xhr) { 
    cache[ term ] = $.map(data, function(item) { 
     return { 
      label: item.name, 
      value: item.name, 
      slug: item.slug, 
      name: item.name 
     }; 
    }); 
    if (xhr === lastXhr) { 
     response(data); 
    } 
}); 

這應該使結果顯示正常(和緩存應該還是工作得很好)。再舉一個例子,請查看remote JSONP example

+0

謝謝。這工作。 – jwinn

+0

對於任何引用此問題的用戶,如果第一次加載自動完成時出現問題,只有在刪除並重新輸入後,纔將最後一位更改爲此,因爲映射數據僅保存在緩存變量中: ' if(xhr === lastXhr){response(cache [term]); }' – jwinn