Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve XHR response code (+timestamp) of AMD'ized Dojo?

With the "old" Dojo one could pass a second argument ioargs to the load function of a Xhr request (see Example 6 here). This ioargs provided (among other things) the timestamp and status code of the request.

But how can I achieve this with the new and "cleaner" (and forward compatible) Dojo?
Unfortunately, I could not find any hints in the current documentation.

The following should be a port of above referenced example to the "new" Dojo. But, ioargs will be undefined:

require( "dojo/request/xhr", "dojo/dom", "dojo/domReady!",
  function(request, dom){
    // Look up the node we'll stick the text under.
    var targetNode = dom.byId("getLicenseStatus");

    // The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
    request.get(
      "{{dataUrl}}dojo/LICENSE",
      {
        handleAs: "text",
        preventCache: true
      }
    ).then(
      function(data, ioargs){
        // FIXME: ioargs is undefined
        targetNode.innerHTML = "XHR returned HTTP status: " + ioargs.xhr.status;
      },
      function(error){
        targetNode.innerHTML = "An unexpected error occurred: " + error.response.status + ": " + error.response.text;
      }
    );
  }
);

What do I need to change to have the request's timestamp and status code available in the load function?

like image 328
Torbjörn Avatar asked Aug 28 '12 07:08

Torbjörn


1 Answers

request returns a special promise (source):

Promises returned from dojo/request calls have an additional property not available on standard promises: response. This property is a promise that will resolve to a frozen object (where available) describing the response in more detail:

  • url – final URL used to make the request (with query string appended)
  • options – options object used to make the request
  • text – string representation of the data in the response
  • data – the handled data in the response (if handleAs was specified)
  • getHeader(headerName) – a function to get a header from the request; if a provider doesn’t provide header information, this function will return null.

So you should chain .then to this promise.response to get access to all the aforementioned properties:

var promise = request.get("{{dataUrl}}dojo/LICENSE");

promise.response.then(function(response) {
    console.log("status", response.status);
    console.log("url", response.url);
    console.log("data", response.data);
});

See a working example at jsFiddle: http://jsfiddle.net/phusick/6wB2L/

like image 52
phusick Avatar answered Nov 02 '22 08:11

phusick