如何使用ajax自动完成

时间:2014-12-06 22:12:38

标签: javascript php jquery ajax jquery-ui

即时通讯使用jqueryui的自动完成功能(http://jqueryui.com/autocomplete/#remote) 而来源来自“来源:”search.php“”

此代码......

 $( "#name" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
}); 
..这下面的代码一起工作得非常好! 但自动完成建议我“我所有的数据”!不像我的任期一样。

<?php
require('inc/tunel.php');
$keyword = $_POST['keyword'];
$respons = array();
$fetch_engine = $db->query("SELECT name FROM `engine`");
    while($read_engine = $fetch_engine->fetch(PDO::FETCH_ASSOC)) {
        $respons[] = $read_engine['name'];
        }

        echo json_encode($respons);
 ?>

我也在下面尝试了这个代码,我的问题解决了,但我不想在我的文档的“查看源代码”中看到我的数据!

$( "#name" ).autocomplete({
source: <?php
	require('inc/tunel.php');

	$respons = array();
	$fetch_engine = $db->query("SELECT name FROM `engine`");
		while($read_engine = $fetch_engine->fetch(PDO::FETCH_ASSOC)) {
			$respons[] = $read_engine['name'];
			}
			
			echo json_encode($respons);
			

?>,
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
}); 

1 个答案:

答案 0 :(得分:0)

您应该创建一个本地服务,接受带有子字符串的参数(在我的示例参数q中至少包含2个字符)并返回带有可能标记的json,然后将其作为ajax用于自动完成的源代码中调用


    $( "#name" ).autocomplete({
          source: function( request, response ) {
           $.ajax({
              url: "http://yourwebservice.com/search",
              dataType: "jsonp",
              data: {
                q: request.term
              },
              success: function( data ) {
                response( data );
              }
            });
          },
          minLength: 2
        });