views:

434

answers:

1

As a fix for this issue, I was wondering if anyone knows of a way to modify the URL of an XMLHttpRequest object prior to sending it.

Ideally, I want to change the uri (encode it) in the beforeSend event (using jQuery $.ajaxSetup) instead of changing it in every location where I'm using $.ajax

Thanks!

A: 

According to the documentation, the beforeSend() method is passed the XMLHttpRequest object as a parameter, and its this pointer is set to the Ajax request options. The XMLHttpRequest doesn't have an attribute that is the URL, but the W3C documentation seems to say that the object's open() method can be called multiple times on a given instance:

beforeSend: function(xhr) {
    // if you're doing authenticated requests, you might have to
    // call the 5-argument form of open() instead
    xhr.open(this.type, this.url.replace( /* whatever with whatever... */ ), this.async);
  }

One potential issue with doing this is that calling open() clears all of the request headers that have been set, so you may have to add some additional code in there to re-add the headers that jQuery sets before invoking beforeSend().

EDIT: Sure enough. Now that I've taken a look at the jQuery source, you're right: the URL is set before the beforeSend() method is invoked. Hopefully the revisions above will work for you.

Sixten Otto
That's what I tried first, but the XMLHttpRequest object has already been constructed by this time and so editing the url in the request options doesn't work. I need to edit the 'xhr' instance passed in.
psychotik