C# jquery ui自动完成值未显示在文本框中
我正在开发一个连接到Google搜索设备的JQuery UI自动完成小部件。我已经使用Fiddler和Visual Studio 2010内置测试工具对该小部件进行了测试,并可以验证输入的查询是否返回了结果 我的问题是,即使返回结果,它们也不会显示在文本框中,目前我使用JQuery和ashx web处理程序的组合来检索和显示结果,下面是JQuery和处理程序的代码: JQueryC# jquery ui自动完成值未显示在文本框中,c#,jquery-ui,jquery-ui-autocomplete,ashx,C#,Jquery Ui,Jquery Ui Autocomplete,Ashx,我正在开发一个连接到Google搜索设备的JQuery UI自动完成小部件。我已经使用Fiddler和Visual Studio 2010内置测试工具对该小部件进行了测试,并可以验证输入的查询是否返回了结果 我的问题是,即使返回结果,它们也不会显示在文本框中,目前我使用JQuery和ashx web处理程序的组合来检索和显示结果,下面是JQuery和处理程序的代码: JQuery <html lang="en"> <head> <meta charset="utf-
<html lang="en">
<head>
<meta charset="utf-8" />
<title>GSA Autocomplete Widget</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/content/styles.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script type="text/javascript">
$(function () {
var cache = {};
$("#programmes").autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("handlers/Suggest.ashx", request, function (data, status, xhr) {
cache[term] = data;
response(data);
});
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="programmes">Programmes: </label>
<input id="programmes" />
</div>
</body>
</html>
GSA自动完成小部件
.ui自动完成加载{
背景:白色url('images/ui-anim_basic_16x16.gif')右中心不重复;
}
$(函数(){
var cache={};
$(“#程序”)。自动完成({
最小长度:2,
来源:功能(请求、响应){
var term=request.term;
if(缓存中的术语){
响应(缓存[术语]);
返回;
}
$.getJSON(“handlers/Suggest.ashx”,请求,函数(数据,状态,xhr){
缓存[术语]=数据;
答复(数据);
});
}
});
});
方案:
ASHX处理器
public class Suggest : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (string.IsNullOrEmpty(context.Request.QueryString[_QUERY_PARAM]))
throw new Exception(string.Format("Could not find parameter '{0}'", _QUERY_PARAM));
// Get the suggestion word from the parameter
string term = context.Request.QueryString[_QUERY_PARAM];
// Create an URL to the GSA
string suggestionUrl = SuggestionUrl(term);
// Call the GSA and get the GSA result as a string
string page = GetPageAsString(suggestionUrl);
// Convert the GSA result to Json
string data = ConvertToJson(page);
// Return the JSON
context.Response.Write(data);
context.Response.End();
}
private string SuggestionUrl(string term)
{
// You should modify this line to connect to your
// own GSA, using the correct collection and frontend
return "http://google4r.mc.man.ac.uk/suggest?max=10&site=mbs_collection&client=mbs_frontend&access=p&format=rich&q=" + term;
}
private string GetPageAsString(string address)
{
// Add your own error handling here
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
private string ConvertToJson(string gsaSuggestResult)
{
bool isFirst = true;
StringBuilder sb = new StringBuilder();
sb.Append("{ query:");
foreach (string token in ParseGsaInput(gsaSuggestResult))
{
if (isFirst)
{
sb.AppendFormat("'{0}', suggestions:[", token.Trim());
isFirst = false;
}
else
{
sb.AppendFormat("'{0}',", token.Trim());
}
}
sb.Remove(sb.Length - 1, 1);
sb.Append(@"]}");
return sb.ToString();
}
private IEnumerable<string> ParseGsaInput(string gsaSuggestResult)
{
gsaSuggestResult = gsaSuggestResult.Replace("[", "").Replace("]", "").Replace("\"", "");
return gsaSuggestResult.Split(',');
}
private const string _QUERY_PARAM = "term";
}
公共类建议:IHttpHandler
{
公共布尔可重用
{
获取{return true;}
}
公共void ProcessRequest(HttpContext上下文)
{
if(string.IsNullOrEmpty(context.Request.QueryString[\u QUERY\u PARAM]))
抛出新异常(string.Format(“找不到参数“{0}”,_QUERY_PARAM));
//从参数中获取建议词
string term=context.Request.QueryString[\u QUERY\u PARAM];
//创建指向GSA的URL
字符串suggestionUrl=suggestionUrl(术语);
//调用GSA并将GSA结果作为字符串获取
string page=GetPageAsString(suggestionUrl);
//将GSA结果转换为Json
字符串数据=ConvertToJson(第页);
//返回JSON
context.Response.Write(数据);
context.Response.End();
}
私有字符串建议URL(字符串术语)
{
//您应该修改此行以连接到您的
//拥有GSA,使用正确的收藏和前端
返回“http://google4r.mc.man.ac.uk/suggest?max=10&site=mbs_collection&client=mbs_frontend&access=p&format=rich&q=“+任期;
}
私有字符串GetPageAsString(字符串地址)
{
//在此处添加您自己的错误处理
HttpWebRequest-request=WebRequest.Create(address)为HttpWebRequest;
使用(HttpWebResponse=request.GetResponse()作为HttpWebResponse)
{
StreamReader=新的StreamReader(response.GetResponseStream());
返回reader.ReadToEnd();
}
}
私有字符串ConvertToJson(字符串gsaSuggestResult)
{
bool isFirst=true;
StringBuilder sb=新的StringBuilder();
sb.追加(“{query:”);
foreach(ParseGsaInput(gsaSuggestResult)中的字符串标记)
{
如果(isFirst)
{
sb.AppendFormat(“{0}”,建议:[”,token.Trim());
isFirst=false;
}
其他的
{
sb.AppendFormat(“{0}”,token.Trim());
}
}
移除(sb长度-1,1);
某人附加(@“]}”);
使某人返回字符串();
}
私有IEnumerable ParseGsaInput(字符串gsaSuggestResult)
{
gsaSuggestResult=gsaSuggestResult.Replace(“[”,”).Replace(“]”,”).Replace(“\”,”);
返回gsaSuggestResult.Split(',');
}
private const string_QUERY_PARAM=“term”;
}
目前,JSON结果返回名称和类型
如何将web处理程序的结果绑定到文本框?我建议您按原样(除非您有其他修改要求)将从源收集的数据返回到客户端,如下所示:
public void ProcessRequest(HttpContext context)
{
if (string.IsNullOrEmpty(context.Request.QueryString[_QUERY_PARAM]))
throw new Exception(string.Format("Could not find parameter '{0}'", _QUERY_PARAM));
// Get the suggestion word from the parameter
string term = context.Request.QueryString[_QUERY_PARAM];
// Create an URL to the GSA
string suggestionUrl = SuggestionUrl(term);
// Call the GSA and get the GSA result as a string
string page = GetPageAsString(suggestionUrl);
context.Response.Write(page);
//Should inform about the content type to client
context.Response.ContentType = "application/json";
context.Response.End();
}
然后在客户端根据自动完成要求格式化响应
$(function () {
var cache = {};
$("#programmes").autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("/Suggest.ashx", request, function(data, status, xhr) {
var suggestions;
suggestions = $.map(data.results, function(item) {
return { label: item.name, value: item.name };
});
cache[term] = suggestions;
response(suggestions);
});
}
});
});
希望这有帮助