-
-
Save donfrancisco/2837830 to your computer and use it in GitHub Desktop.
Call an external JSON API via a local cross domain proxy
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
// 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