Created
July 31, 2012 01:03
-
-
Save gavinballard/3212413 to your computer and use it in GitHub Desktop.
Add an 'addParameters' method to Prototype's Ajax.Request, allowing eg onCreate() callbacks to append parameters to requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ajax.Request.addMethods({ | |
/** | |
* Add the values given in the argument hash to an existing Ajax.Request. | |
* This method operates by extending the existing 'parameters' property | |
* on the request, then re-encoding that hash and either updating the | |
* generated URL (for GET requests) or simply setting the 'postBody' | |
* option on the request (for POST and other requests). | |
* | |
* @param parameters A hash of new parameters to extend the request with. | |
*/ | |
addParameters: function(parameters) { | |
// Add new parameters to the parameters hash. | |
Object.extend(this.parameters, parameters); | |
// Append to querystring if a GET request, otherwise set as postBody option param. | |
if(this.method === 'get') { | |
// Extract current query parameters if they exist and extend them with new parameters. | |
var params = Object.extend(this.url.include('?') ? this.url.toQueryParams() : {}, this.parameters); | |
// Trim any existing query parameters off the end of the URL. | |
this.url.include('?') && (this.url = this.url.slice(0, this.url.indexOf('?'))); | |
// Add the new, encoded parameters. | |
this.url += '?' + Object.toQueryString(params); | |
} else { | |
// Just encode and add the new parameters hash to the postBody. | |
this.options.postBody = Object.toQueryString(this.parameters); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment