$.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);
}
})
where data is
["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));
}
but if i search by word “so” i don’t get anything.
If ws return
[WebMethod]
public string GetSuggestedRestaurants(object prefixText)
{
return "Aeroplane dkhashd Apple Ambulance Border Crops Desalination Elephants Parrot ";
}
and js looks like
data = msg.d.split(" ");
alert(data)
then data looks like
Aeroplane,dkhashd,Apple,Ambulance,Border,Crops,Desalination,Elephants,Parrot
and autosuggest work. What is worng with first json if data is
["some text","another some textz","huh just text"]
Your first error is that the text
is NOT valid JSON string. It could be correct object initializer in JavaScript, but it is wrong encoded JSON corresponds to http://www.json.org/ and RFC4627. Correct JSON string will be
or the following
in your case (with some small possible problems if
$('#ctl00_ctl00_cplMPBody_txtSearch').val()has " or \ characters inside). I recommend you http://www.jsonlint.com/ site where you can validate any JSON data.The next problem is on the server side. The ASMX web method should be like the following
and the corresponding class should has
[ScriptService]attribute.I recommend you to use
JSON.stringifymethod:instead of manual JSON serialization. See details in my other answer which include link to the working demo project.