我有一个带有以下代码的jQuery自动完成字段:
var tags = ["a","ab","abc","abcd","adbce","abcdef","abcdefg","abcdefgh","abcdefghi","abcdefghij","abcdefghijk","abcdefghijkl","abcdefghijklm","abcdefghijklmn","abcdefghijklmno","abcdefghijklmnop","abcdefghijklmnopq","abcdefghijklmnopqr","abcdefghijklmnopqrs","abcdefghijklmnopqrst",]; $("input#name").autocomplete({ position: { offset: "0 -10px",},source: tags });
它使用’tags’数组作为样本输入数据正常工作.
现在我需要有一组MySQL查询结果而不是该示例数组.我做的是将函数调用更改为:
$("input#name").autocomplete({ position: { offset: "0 -10px",source: "http://absolutepathtofile/autosuggest.PHP" });
我使用绝对路径确保我没有在那里犯一些愚蠢的错误,因为我无法将文件返回到自动完成中.我去过jQuery文档并找到了一些使用PHP / MysqL返回自动完成结果的例子,但是我无法让它工作.
这是我在autosuggest.PHP中尝试过的:
$term = $_REQUEST['term']; $query = "SELECT * FROM merchants WHERE business_name LIKE '%$term%'"; $result = MysqL_query($query); $k=0; while($row=MysqL_fetch_array($result)){ $aUsers[$k]=$row['business_name']; $k++; } echo json_encode($aUsers);
我尽可能简单但它没有用.
然后我测试了JSON是否被发送,所以我做了这个:
$array[0]="test"; $array[1]="test1"; echo json_encode($array);
它不起作用.我在任何地方都找不到这个问题,我做错了什么? PHP版本是5.3.10,它有json_encode(之前使用过它).
解决方法
$.ajax({ url:"http://absolutepathtofile/autosuggest.PHP",type:"post",success:function(html){ $("#user_phone").autocomplete( {position: {offset: "0 -10px"},source: html }); } });
>为我工作和测试