2014-04-25 68 views
0

我正在嘗試使用基本的自動完成和Ajax。我無法理解結果。我相對較新的jQuery,所以我爲我的語法道歉,我更擅長於PHP。使用Ajax的jQuery自動完成不會解析

$("#category_title").autocomplete({ 
    source: function (request, response) { 
    $.ajax({ 
     url: 'index.php?controller=AdminEvents&action=AutoComplete&variable=asdf', 
     type: 'GET', 
     success: function(data){ 
     response(data); 
     } 
    }); 
    }, 
    minLength: 2 
}); 

從控制器的響應是樣本數據,實際上並沒有從數據庫中獲取任何東西:

if ($this->isXHR()) 
{ 
    //$response = "{value1:test, value2:test2}"; 
    $response['value1'] = "test"; 
    $response['value2'] = "test2"; 
    $json = json_encode($response); 
    print($json); 
} 

這裏是一個很奇怪我的一部分。這基本上,這個工程並自動完成框彈出,但這裏就是它的回報呢:

enter image description here

爲什麼?

謝謝你的時間!

回答

0

試試這個:

jQuery的

$(document).ready(function(){ 
    $('#zipsearch').autocomplete({source:'suggest_zip.php', minLength:2}); 
}); 

PHP

$response = array(); 
$response[0]=array('label'=>'test','value'=>'test'); 
$response[1]=array('label'=>'test2','value'=>'test2'); 
echo json_encode($response); 
+0

相同的結果。 – Joe

+0

這裏是一個例子,檢查它,它的工作原理。 http://www.htmlblog.us/jquery-autocomplete –

+0

請參閱我嘗試採用我認爲你想說的話,我沒有興趣將我寫的所有內容都替換爲「解決它」。我想弄清楚什麼是錯的,所以我可以理解。 – Joe

0

可能這可以幫助你

jQuery的

$("#zipsearch").autocomplete({ 
        source: function(req,res) { 
         $.ajax({ 
          url: "index.php?controller=AdminEvents&action=AutoComplete&variable=asdf", 
          dataType: "json", 
          type: "GET", 
          data: { 
           term: req.term 
          }, 
          success: function(data) { 
           res($.map(data, function(item) { 
            return { 
             label: item.value1, 
             value: item.value1 
            }; 
           })); 
          }, 
          error: function(xhr) { 
           alert(xhr.status + ' : ' + xhr.statusText); 
          } 
         }); 
        } 
       }); 

PHP從這個

<?php 
$response=array(); 
$response[0]['value1'] = "test"; 
$response[1]['value1'] = "test2"; 
print json_encode($response); 
?>