2014-06-10 93 views
0

我從ajax獲取數據,但我想用jquery自動完成如何使用jQuery的自動完成功能與Ajax?

我使用自動完成填寫文本框中的名稱。從AJAX

{ 
"id": "2", 
"name": "Jenny Doe", 
"phone": "", 
"email": "[email protected]", 
"password": null, 
"registered": "2014-04-11 15:06:02", 
"address": "", 
"email_subscription": "0", 
"email_verified": "0", 
"reset_password": null, 
"facebook_uid": null, 
"title": "", 
"phone2": "", 
"gender": null, 
"booking_date": "0000-00-00", 
"birthday": "0000-00-00", 
"nationality": "", 
"passport": "" 
}, 

數據我想告訴顧客的名字時,我在輸入框中單擊。 我想知道如何使用ajax和自動完成來解決這個問題。

jQuery代碼

$('.customer').on('click', '.customer_name', function(){ 
     var name = $(this).val(); 
     var customer_url = '/api/users?name_fulltext' + name; 
     console.log(customer_url); 
     $.getJSON(customer_url, function(data){ 
      customer_cache[name]= []; 
      for (var j in data) { 
       //index the results by id 
       customer_cache[name][data[j]["name"]] = data[j]; 
       var customer_name = customer_cache[name][data[j]["name"]]; 
      } 
     }); 

     $('.customer_name').autocomplete({ 
     }); 
}); 

回答

1
 $("#element_id").autocomplete({ 
       source: function(request, response) { 
        $.get("Ajax Url", 
        { 
         query: request.term 
        },function (data) { 
         var d = JSON.parse(data); 
         response(d); 
        }); 
       }, 
       select: function(event, ui) { 
        //do something nice 
        return false; 
       }, 
       minLength: 1, 
      }) 
      .data("ui-autocomplete")._renderItem = function(ul, item) { 
       return $("<li>") 
       .append("<a>" + item.name +"</a>") 
       .appendTo(ul); 
      }; 
1

jQuery用戶界面autocomplete期待與labelvalue屬性對象。這裏用label來顯示,value是值。

下面是樣品autocomplete代碼

var cache = {}; 
$(".customer_name").autocomplete({ 
     minLength: 2, 
     mustMatch: true, 
     focus: function (event, ui) { 
      //ui.item.label contains value 
      return false; 
     }, 
     change: function (event, ui) { 
      if (!ui.item) { 
       $(".customer_name").focus(); 
       $(".customer_name").val(""); 


      } 

     }, 
     select: function (event, ui) { 
      var val= ui.item.value; 
      return false; 
     }, 
     source: function (request, response) { 
      var term = request.term; 
      if (term in cache) { 
       response(cache[term]); 
       return; 
      } 
      $.ajax({ 
       url: url 
       contentType: 'application/json; charset=utf-8', 
       type: 'GET', 
       data: "{'keywords':'" + request.term + "'}", 
       dataType: 'json', 
       error: function (xhr, status) { 
        //error occured 
       }, 
       success: function (data) { 
        cache[term] = data; 
        response(data); 
       } 
      }); 
     } 
    }); 

http://jqueryui.com/autocomplete/