Reputation: 361
i'm developing an web application in .net platform.
i have wrote an Handler code that return a JSON object to Javascript (after i request in AJAX).
the Handler code:
var wrapper = new {
left = left.ToString(),
top = top.ToString(),
width = width.ToString(),
height = height.ToString() };
context.Response.Write(JsonConvert.SerializeObject(wrapper));
In Javascript, when i do alert, i see that i get an object. and it's good.
But now i want to parse it to JSON.
when i do JSON.parse(msg);
i get an error
"JSON.parse: unexpected character"
when i do jQuery.parseJSON(msg);
using jquery-1.6.2, i get this error
jQuery.parseJSON is not a function (i'm using jquery-1.6.2)
What is the problem?
Upvotes: 2
Views: 4380
Reputation: 55248
Try this.
Create a page called TestPage.aspx like this.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'TestPage.aspx/GetDimensions',
type: 'POST',
contentType: 'application/json',
data: '{}',
success: function (response) {
// Don't forget that the response is wrapped in a
// ".d" object in ASP.NET 3.5 and later.
var data = response.d;
$('#test-div').animate({
left: data.left + 'px',
top: data.top + 'px',
height: data.height + 'px',
width: data.width + 'px'
}, 5000, function () {
// Animation complete.
});
}
});
});
</script>
<style type="text/css">
#test-div
{
background-color:#eee;
border: 1px solid #ccc;
border-radius: 5px;
height: 100px;
left:0px;
padding-top: 40px;
text-align:center;
top:0px;
width: 100px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="test-div">
This is a test div
</div>
</form>
</body>
</html>
And on TestPage.aspx.cs, do this
using System.Web.Services;
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e){/*page load eent*/}
static int left = 50;
static int top = 50;
static int height = 200;
static int width = 200;
[WebMethod]
public static object GetDimensions()
{
return new
{
left = left.ToString(),
top = top.ToString(),
width = width.ToString(),
height = height.ToString()
};
}
}
Hope this helps.
Courtesy: ASP.NET web services mistake: manual JSON serialization by Dave Ward
Upvotes: 2