代码之家  ›  专栏  ›  技术社区  ›  Vivian River

为什么我需要使用.d来访问jquery ajax返回的数据?

  •  10
  • Vivian River  · 技术社区  · 15 年前

    我使用了一些在互联网上找到的教程,编写了一些jQueryAjax代码。我刚接触jquery,想学习如何做得更好。我有一个同事,他用大量jquery构建了一个漂亮的Web应用程序。

    我在这里最困惑的是:为什么在提到我的web方法的响应时必须使用“.d”,它代表什么?

        // ASP.net C# code
        [System.Web.Services.WebMethod]
        public static string hello()
        {
            return ("howdy");
        }
    
    // Javascript code
    function testMethod() {
        $.ajax({
            type: "POST",
            url: "ViewNamesAndNumbers.aspx/hello",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                alert(msg);   // This doesn't display the response.
                alert(msg.d); // This displays the response.
            } // end success:
        }) // end $.ajax
    
    3 回复  |  直到 15 年前
        1
  •  13
  •   Samuel Cole    15 年前

    它是在ASP.NET 3.5S版本的ASP.NET AJAX中添加的,以防止您受到此漏洞的攻击: http://haacked.com/archive/2009/06/25/json-hijacking.aspx

    (答案来源于 http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ )

        2
  •  5
  •   Mike Florian Doyen    15 年前

    Microsoft这样做是为了保护您免受安全漏洞的攻击。见 This Page 更多信息。

        3
  •  4
  •   jAndy    15 年前

    我猜 alert(msg) 显示“[对象对象]”?

    如果是这样的话,是因为被解析的对象 window.JSON (当指定 json 作为数据类型)确实看起来:

    object = {
        d:   "some data"
    }
    

    检查在viewname和numbers.aspx/hello中生成的内容