开发者

Why do I need to use .d to access data returned by jQuery AJAX?

开发者 https://www.devze.com 2023-01-19 18:06 出处:网络
I\'ve put toget开发者_运维百科her some jQuery AJAX code using some tutorials I found on the internet.I\'m new to jQuery and want to learn how to do things betters.I have a coworker who put together a

I've put toget开发者_运维百科her some jQuery AJAX code using some tutorials I found on the internet. I'm new to jQuery and want to learn how to do things betters. I have a coworker who put together a beautiful web application using a lot of jQuery.

The thing I'm most confused about here is: why is it necessary to use the ".d" when referring to the response of my web method and what does it stand for?

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


It was added in ASP.NET 3.5’s version of ASP.NET AJAX to prevent you from being vulnerable to this exploit: http://haacked.com/archive/2009/06/25/json-hijacking.aspx

(Answer sourced from http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/)


Microsoft does this to protect you from a security exploit. See the bottom of This Page for more information.


I guess alert(msg) displays "[object Object]" ?

If so it's because the object which is parsed through window.JSON (which happens under the hood when specifying json as dataType) does really look:

object = {
    d:   "some data"
}

Check what you are generating in ViewNamesAndNumbers.aspx/hello

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号