我想实现一个简单WebMethod
在C#中搜索的50,000人分贝。 我使用Twitter的引导bloodhound.js
和typeahead.js
来标记,并自动完成的响应。
当我运行这段代码,预输入显示了一个下拉菜单undefined
。
我怎样才能正确处理JSON响应剥离出d
通过.NET返回的对象WebMethod
和正确地传递我的记录警犬? 我已经试过这使用dataFilter
由jQuery的提供的方法$.ajax
,但它不是为我工作。
C#的WebMethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object searchStaffByName(string q)
{
using (App_Data.DQDBDataContext dc = new App_Data.DQDBDataContext())
{
var results = dc.getStaffDetails(q).ToList();
return new { Status = "OK", Records = results, Count = results.Count };
}
}
预输入JS实现:
var textlookup = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'Search.aspx/searchStaffByName',
replace: function (url, query) {
searchQuery = query;
return url;
},
ajax: {
beforeSend: function (jqXhr, settings) {
settings.data = JSON.stringify({
q: searchQuery
});
jqXhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
},
dataFilter: function (data, type) {
if (type === "json") {
data = $.parseJSON(data);
if (typeof data.d === 'object' && data.d.Count > 0) {
return data.d.Records;
}
}
},
type: 'POST'
}
}
});
textlookup.initialize();
$('.autocomplete').typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'textlookup',
displayKey: 'Forename',
source: textlookup.ttAdapter()
});
样品JSON响应:
{
"d": {
"Status":"OK",
"Records": [{
"id":45711192,
"phone":"514-579-5721",
"Forename":"Jayden",
"Surname":"Adams",
"DOB":"\/Date(990226800000)\/"
},
{
"id":12603644,
"phone":"333-143-9094",
"Forename":"Jake",
"Surname":"Adams",
"DOB":"\/Date(43542000000)\/"
},
{
"id":68196438,
"phone":"440-505-2403",
"Forename":"Josh",
"Surname":"Adams",
"DOB":"\/Date(-51152400000)\/"
}],
"Count":6
}
}