2010-05-04 130 views
1

只從今天開始,但我遇到了大量問題,試圖理解JSON/AJAX等,我已經得到了我的代碼到目前爲止,但難以知道如何返回正在被AJAX請求到jQuery Auto完成功能。 [ 「UGA」, 「UK4」, 「全球不包括美國,加拿大和加勒比海」]:JSON + PHP + JQuery +自動完成問題

var autocomplete = new function(){ 
this.init = function() { 
    $('#insurance_destination').autocomplete({source: lookup}); 
} 

    function lookup(){ 
    $.ajax({ 
     url: "scripts/php/autocomplete.php", 
     data: {query:this.term}, 
     dataType: "json", 
     cache : false, 
     success: function(data) {  
      for(key in data){ 
       return { 
        label: key, 
        value: data[key][0] 
        } 
      }          
     }  
}); 
} 

}

和示例JSON字符串由PHP腳本 { 「烏干達」 返回}

回答

1

通常情況下,你不必做AJAX查詢自己:

$('#insurance_destination').autocomplete('url_here', {options_here}); 

這是假設我們談論標準的jQuery自動完成插件。我理解正確嗎?

編輯 檢查API
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
也有一些例子。

+0

我也嘗試太,但它似乎沒有不工作要麼......這可能是我的PHP的問題,儘管使用手動代碼它返回的JSON字符串似乎工作正常,但我無法讓自動填充框填充數據。 – RohanCS 2010-05-04 20:59:27

+1

它不應該採用json,值應該用換行符分隔。查看這個頁面的例子,特別是提供的示例php腳本:http://view.jquery.com/trunk/plugins/autocomplete/demo/ 讓我知道它是否有幫助。 – 2010-05-04 22:52:04

0

這是我已經結束了的代碼,它工作於Chrome和Firefox,但不是在IE 6/7 ...

var autocomplete = new function(){ 
    this.init = function() { 
     $('#insurance_destination').autocomplete({ 
      source: function(request, response) { 
       debugger; 
       $.ajax({ 
        url: "scripts/php/autocomplete.php", 
        dataType: "json", 
        data: {query:this.term}, 
        success: function(data) { 
        response($.map(data.countries, function(item) { 
         return { 
          label: '<strong>'+item.name+'</strong>'+' '+item.description, 
          value: item.name, 
          code : item.region 
         } 
        })) 
       } 
      }) 
     }, 
     minLength: 2, 
     select: function(event, ui) { 
      $('#insurance_iso_code_hidden').val(ui.item.code); 
     }, 
     open: function() { 
     }, 
     close: function() { 

     } 
     }); 
    } 


    }