autosuggest,ws和json问题

$.ajax({ type: "POST", url: "/webservices/AutoSuggestWebService.asmx/GetSuggestedRestaurants", data: "{'prefixText': '" + $('#ctl00_ctl00_cplMPBody_txtSearch').val() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { data = msg.d; alert(msg.d) $("#ctl00_ctl00_cplMPBody_txtSearch").autocomplete(data); } }) 

数据在哪里

 ["some text","another some textz","huh just text"] 

WS:

 [WebMethod] public string GetSuggestedRestaurants(object prefixText) { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(new RestaurantSearchHelper(DaoFactory).GetSearchSuggest(prefixText.ToString(), PageBase.CurrentCountry)); } 

但如果我用“so”这个词搜索,我什么也得不到。

如果回归

 [WebMethod] public string GetSuggestedRestaurants(object prefixText) { return "Aeroplane dkhashd Apple Ambulance Border Crops Desalination Elephants Parrot "; } 

和js看起来像

 data = msg.d.split(" "); alert(data) 

然后数据看起来像

 Aeroplane,dkhashd,Apple,Ambulance,Border,Crops,Desalination,Elephants,Parrot 

和autosuggest工作。 如果有数据,第一个json的内容是什么?

 ["some text","another some textz","huh just text"] 

你的第一个错误就是文字

 {'prefixText': 'bla bla'} 

是无效的JSON字符串。 它可能是JavaScript中正确的对象初始化程序 ,但它是错误的编码JSON对应于http://www.json.org/和RFC4627 。 正确的JSON字符串将是

 {"prefixText": "bla bla"} 

或以下

 data: '{"prefixText": "' + $('#ctl00_ctl00_cplMPBody_txtSearch').val() + '"}' 

在你的情况下(如果$('#ctl00_ctl00_cplMPBody_txtSearch').val()有一些小问题$('#ctl00_ctl00_cplMPBody_txtSearch').val()里面有“或\字符”。我建议你http://www.jsonlint.com/在哪里可以validation任何JSON数据。

下一个问题是在服务器端。 ASMX Web方法应如下所示

 [WebMethod] [ScriptMethod (ResponseFormat = ResponseFormat.Json)] public List GetSuggestedRestaurants(string prefixText) { return new RestaurantSearchHelper(DaoFactory).GetSearchSuggest( prefixText, PageBase.CurrentCountry); } 

并且相应的类应该具有[ScriptService]属性。

我建议你使用JSON.stringify方法:

 data: JSON.stringify({ prefixText: $('#ctl00_ctl00_cplMPBody_txtSearch').val() }) 

而不是手动JSON序列化。 请参阅我的其他答案中的详细信息,其中包括工作演示项目的链接。