views:

48

answers:

3

I've put together 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
+2  A: 

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

jAndy
+6  A: 

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

Samuel Cole
+2  A: 

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

Mike