$.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“搜索,我什么也得不到。
如果ws返回
[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和自动建议的工作。第一个json有什么问题,如果数据是
["some text","another some textz","huh just text"]发布于 2011-03-02 05:46:42
您的第一个错误是文本
{'prefixText': 'bla bla'}is 不是有效的JSON字符串。JavaScript中的object initializer可能是正确的,但是对应于http://www.json.org/和RFC4627的JSON编码是错误的。正确的JSON字符串将为
{"prefixText": "bla bla"}或以下内容
data: '{"prefixText": "' + $('#ctl00_ctl00_cplMPBody_txtSearch').val() + '"}'在您的例子中(如果JSON内部有“或\”字符,可能会出现一些小问题)。我建议您使用http://www.jsonlint.com/站点,您可以在该站点验证任何$('#ctl00_ctl00_cplMPBody_txtSearch').val()数据。
下一个问题是在服务器端。ASMX web方法应如下所示
[WebMethod]
[ScriptMethod (ResponseFormat = ResponseFormat.Json)]
public List<string> GetSuggestedRestaurants(string prefixText) {
return new RestaurantSearchHelper(DaoFactory).GetSearchSuggest(
prefixText,
PageBase.CurrentCountry);
}相应的类应该有[ScriptService]属性。
建议您使用JSON.stringify方法:
data: JSON.stringify({ prefixText: $('#ctl00_ctl00_cplMPBody_txtSearch').val() })而不是手动JSON序列化。在我的other answer中查看详细信息,其中包括到工作演示项目的链接。
https://stackoverflow.com/questions/5159113
复制相似问题