2

我正在.net 平台上开发一个 Web 应用程序。

我编写了一个将 JSON 对象返回给 Javascript 的处理程序代码(在我在 AJAX 中请求之后)。

处理程序代码:

var wrapper = new { 
    left = left.ToString(), 
    top = top.ToString(), 
    width = width.ToString(), 
    height = height.ToString() };
context.Response.Write(JsonConvert.SerializeObject(wrapper));

在 Javascript 中,当我发出警报时,我看到我得到了一个对象。这很好。
但现在我想将其解析为 JSON。

当我这样做时,JSON.parse(msg);我得到一个错误

“JSON.parse:意外字符”

当我jQuery.parseJSON(msg);使用 jquery-1.6.2 时,出现此错误

jQuery.parseJSON 不是函数(我使用的是 jquery-1.6.2)

问题是什么?

4

1 回答 1

2

试试这个。

像这样创建一个名为 TestPage.aspx 的页面。

<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>

在 TestPage.aspx.cs 上,执行此操作

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()
        };
    }
}

希望这可以帮助。

礼貌:ASP.NET Web 服务错误:Dave Ward 的手动 JSON 序列化

于 2011-07-17T15:56:08.160 回答