我已经尝试Simon Whatley's plugin用于jQuery自动完成,但我发现该插件期望自动完成结果在各行上,并且不需要json。
所以,我搜索了其他接受json的插件,我找到了jQuery UI autocomplete。在文档中,使用json数据的例子并不多。我无法用我的代码完成这项工作。我也寻求其他网站的帮助,但无济于事。
以下是我的查询代码:
<cfif url.q neq ''>
<cfset theQ = lcase(q)>
<cfquery datasource="names" name="qry" maxrows="20">
select top 10 id, name
from sample
where
lower(name) like '#theQ#%'
order by name
</cfquery>
<!---
Before we can serialize the query, we need to convert
it to an array of structs.
--->
<cfset rows = [] />
<!--- Loop over the query to convert it. --->
<cfloop query="qry">
<!--- Create a row struct. --->
<cfset row = {} />
<!--- Add each column to our struct. --->
<cfloop
index="column"
list="#qry.columnList#"
delimiters=",">
<cfset row[ column ] = qry[ column ][ qry.currentRow ] />
</cfloop>
<!--- Append the row struct to the row array. --->
<cfset arrayAppend( rows, row ) />
</cfloop>
<!---
Now that we have converted our query to an
array of structs, we can serialize it using the
serializeJSON() method.
--->
<cfset serialized=#serializeJSON(rows)#>
<cfoutput>#serialized#</cfoutput>
</cfif>
我得到的json数据如下:
[{"NAME":"levi","ID":7},{"NAME":"leviticus","ID":3}]
现在,这里是自动完成:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#q").autocomplete({
source: function(request, response){
$.post("data/country.cfm", {data:request.term}, function(data){
response($.map(data, function(item) {
return {
label: item.id,
value: item.name
}
}))
}, "json");
},
minLength: 2,
dataType: "json",
cache: false,
focus: function(event, ui) {
return false;
},
select: function(event, ui) {
this.value = ui.item.label;
return false;
}
});
});
</script>
问题是什么?有什么帮助吗?谢谢。