我想使用 jquery 自动完成功能。数据来自一个以 json 格式返回数据的 web 服务。但相关 texbox 中的输出不起作用。我显示了完整的 json 数组。
请给我一个提示。
我的网络服务看起来像:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;
namespace WebApplication1
{
/// <summary>
/// Zusammenfassungsbeschreibung für WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string customer(string queryParam)
{
string conStr=
ConfigurationManager.ConnectionStrings["mySql_classicmodels"].ConnectionString;
MySqlConnection con = new MySqlConnection(conStr);
MySqlCommand readCommand = new MySqlCommand("SELECT customerName, contactLastName, contactFirstName, phone FROM customers where customerName like '%" + queryParam + "%'", con);
MySqlDataAdapter adapter = new MySqlDataAdapter(readCommand);
DataTable datatable = new DataTable();
adapter.Fill(datatable);
return DataTableToJSON(datatable);
}
public static string DataTableToJSON(DataTable table)
{
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow row in table.Rows)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
dict[col.ColumnName] = row[col];
}
list.Add(dict);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
}
}
我的 ASP / JQuery 代码如下所示:
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "Webservice1.asmx/customer",
dataType: "json",
data: '{ queryParam: "' + request.term + '" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
value:item
}
}));
},
minLength: 2,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
alert(xhr.responseText);
}
});
}
})
})
</script>
我的结果是这样的:
[{"customerName":"Australian Collectors, Co.","contactLastName":"Ferguson","contactFirstName":"Peter","phone":"03 9520 4555"},{"customerName":"Australian Gift Network, Co","contactLastName":"Calaghan","contactFirstName":"Ben","phone":"61-7-3844-6555"},{"customerName":"Australian Collectables, Ltd","contactLastName":"Clenahan","contactFirstName":"Sean","phone":"61-9-3844-6555"}]
怎么了?