When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The response I see from Firebug is: {"d":"{\"Item\":\"Testing\"}"} . I understand that the backslash is used to escape the double quote, but how can I fix this problem with the JSON format? I have spent 3 days searching on Google, but it seems like others are experiencing the same issue. Any help would be greatly appreciated.
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);
}
});
}