2014-04-25 42 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); 
?>