Circumventing browser same origin policy with a proxy in Rails 3 application
I'm looking for a rails solution that can consume multiple remote XML services, passing dynamic request parameters and outputting the response as XML or JSON.
I've looked into TinyProxy (Can't get it to install on OSX via macports) and also Nginx. Ngin开发者_JAVA百科x looks like it will do what I need and also give us flexibility going forward with load balancing etc.
Has anyone else got any experience of this? Any tried and tested solutions?
In stead of going through a proxy, one of the standard solutions around the same-origin policy is dynamic script tags and JSON callbacks.
For example: you page page wants to query an API at remotesite.com and you try to do an ajax call to http://remotesite.com/api?query=list but you get the same-origin error. To circumvent the restriction you could add a script tag to the DOM (using JS) that points to the url like this:
var e = document.createElement('script');
e.src = 'http://remotesite.com/api?query=list';
document.getElementById('fb-root').appendChild(e);
The browser would then run that request - the same thing you tried to do w/ an ajax call. Now the catch is that you need to have the response call one of your js functions w/ the data returned as a argument. So the request would return something like:
callbackFunctionname({...json_data_here...});
Now in your code you'd have a function like this:
function callbackFunctionname(json_string)
{
//you have result from cross domain ajax request.
}
精彩评论