I am calling a server side function to return a json format string and parse in client side using javascript and ajax. I got parse error at javascript. I think it is the backslash JavaScriptSerializer adds to serialize object. here is the response I see from firebug:
{“d”:”{\”Item\”:\”Testing\”}”} , i understand the backslash is to escape the double quote but how do i get json to fix this problem?? i spend 3 days and do all the search at google. It seems i am doing the same way as others. Thanks for help.
Server side Code:
[System.Web.Services.WebMethod]
public static string testmethod(string serial)
{
ItemList itemlist = new ItemList();
itemlist.Item = "Testing";
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(itemlist);
}
[System.Runtime.Serialization.DataContract]
public class ItemList
{
[System.Runtime.Serialization.DataMember]
public string Item { get; set; }
}
Client Side Javascript with ajax:
function PassParemeterToAspxUsingJquery(serial)
{
var sn = "test";//serial;
$.ajax({
type: "POST",
url: "test.aspx/testmethod",
contentType: "application/json; charset=utf-8",
data: "{serial:'" + sn+"'}" ,
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(jqXHR, textStatus, errorThrown){
alert("The following error occured: "+ textStatus, errorThrown);
alert(jqXHR.responseText);
}
});
}
The
WebMethodwon’t embed the value as part of the JSON text. If you want it serialized as a JSON Object rather than a JSON String, you have to return anObjectrather than aString:Though, this may require .NET 3.5 and a
ScriptMethodAttribute:Then just:
Alternatively, you should be able to work with it as is by parsing
msg.d: