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 jQuery.parseJSON(msg);-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 に答える