Created
May 30, 2012 10:13
-
-
Save ryankirkman/2835327 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 | |
}); |
@ynevet Thanks mate
Hi, you welcome.
Look, I need to post data to another domain and i'm using your code, but the ajax call does't reaching to my proxy action at the server and the browser alerts:
"XMLHttpRequest cannot load http://www.anotherdomain.com/. Origin http://localhost:5432 is not allowed by Access-Control-Allow-Origin."
Any Idea?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Syntax error at 28 line: open curly brace instead of close.
Should change it to: }).success(function(data) {