Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donfrancisco/2837830 to your computer and use it in GitHub Desktop.
Save donfrancisco/2837830 to your computer and use it in GitHub Desktop.
Call an external JSON API via a local cross domain proxy
// See: http://api.jquery.com/jQuery.ajaxPrefilter/
$.ajaxPrefilter( function( options ) {
if ( options.crossDomain ) {
var newData = {};
// Copy the options.data object to the newData.data property.
// We need to do this because javascript doesn't deep-copy variables by default.
newData.data = $.extend({}, options.data);
newData.url = options.url;
// Reset the options object - we'll re-populate in the following lines.
options = {};
// Set the proxy URL
options.url = "http://mydomain.com/proxy";
options.data = $.param(newData);
options.crossDomain = false;
}
});
// How to use the cross domain proxy
$.ajax({
url: 'http://the-real-api-url.com/getdata',
data: {
username: 'myUsername',
password: 'myPassword'
},
crossDomain: true, // set this to ensure our $.ajaxPrefilter hook fires
processData: false // We want this to remain an object for $.ajaxPrefilter, and for performance reasons
{).success(function(data) { // Use the new jQuery promises interface and assume our API call returns a JSON object
var jsonData = JSON.parse(data); // Assume it return a JSON string
console.log(jsonData); // Do whatever you want with the data
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment