0

Is it possible to get the properties of a request (ideally before it's sent) from an XMLHttpRequest object.

For example after calling:

var a = new XMLHttpRequest( );
a.open( 'POST', 'http://localhost/test', true );

how would I then retrieve the method and action url from the object?

9point6
  • 976
  • 2
  • 10
  • 23
  • You have to wrap the request with an object. Frameworks like jQuery do this for you. See related http://stackoverflow.com/questions/921198/get-request-url-from-xhr-object – megawac Nov 11 '13 at 17:27
  • a.open( a.method= 'POST', a.url= 'http://localhost/test', true ); alert(a.url); – dandavis Nov 11 '13 at 17:30
  • Unfortunately I won't always be in control of how open is called. It's for a library for developers to include in their sites. The only option I could think of is overloading the open method, but I was hoping there was a built in ability to grab these properties – 9point6 Nov 11 '13 at 17:33

1 Answers1

1

this worked for me in chrome, firefox and IE10, and will probably work in others as well:

(function(){
 var op=XMLHttpRequest.prototype.open;
 XMLHttpRequest.prototype.open=function(method, url, async){
   this.url=url; 
   this.method=method;
   return op.call(this, method, url, async);
 };
}());

and to make sure it worked:

//demo:
var a = new XMLHttpRequest( );
a.open("GET", "/", false);
a.send();
alert( a.url +"\n\n" + a.responseText);

now, every time you call open(), it memorizes the url and method onto the ajax instance. Since ajax itself is an object, there's no need to wrap an additional object just to tack-on a few properties. I can't think of any downsides to wrapping the ajax object non-obtrusively like this, but maybe someone on here knows of a potential gotcha.

dandavis
  • 16,370
  • 5
  • 40
  • 36