Javascript Ajax响应类型

I'm doing the 70-480 exam, and one of the prep questions was to find the alert output. My guess would be that alert would show "type: undefined". But the supposed correct answer says it shows "type: int".

I'm struggling to understand where I'm failing here. The four points confusing me are:

  • Posting will execute the function in the WebService, however,

  • How is it that the success function response gets a document object? Is this a standard success response for a POST?

  • Doesn't success return true? Or... Is it returning a truthy http code? But then again, how can that relate to a documentElement.localName?

  • Upon a search on Google, I found that localName gives me the name of the node. I haven't seen indication it gives me the type of the object retrieved.

Code below:

[in WebService.asmx]

private int myNumber = 57;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int GetNumber() {
    int diff = new Random().Next(32);
    myNumber = myNumber + diff - 16;
    return myNumber;
}

[in JavaScript]

function getNumber() {
    $.ajax({
        type: "POST",
        url: "/WebService.asmx/GetNumber",
        success: function (response) {
        alert("type: " + response.documentElement.localName);
        }
    });
}

Using jQuery's ajax() function you can specify what format you expect back from server. You can set that expectation using the dataType keyword. Default is intelligent guess, so it tries to make xml, json, script or html out of the response. If none can be guessed, you get a string.

For getting the http return code, use the statusCode keyword, which should be a JSON with HTTP codes as keys and functions as values. Example:

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

As for the success field, the docs are pretty specific about it:

success

Type: Function( Anything data, String textStatus, jqXHR jqXHR )

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function (...)

Consider reading the whole documentation of jQuery's ajax function at http://api.jquery.com/jquery.ajax/

Your web service calls return myNumber; which is an int

When you call your ajax, and it completes successfully, the function you provide in success is called. This function is automatically passed the response from the web service.

In your success function you call response.documentElement.localName which gives you int because the only thing in your response is a single integer

See .documentElement and .localName