I have an app that I’m writing in Javascript for use with Phonegap, that retrieves a JSON encoded string from a PHP script on my server.
Is it possible to retrieve this JSON encoded string from the PHP in Javascript when it’s a cross domain request?
What I’m currently using is Yahoo’s YQL, which retrieves the string through a jQuery AJAX, but I don’t want to have to rely on Yahoo for their service, especially since it’s been very flakey today in terms of uptime.
For Cross Domain GET’s, if you own the endpoint, I recommend modifying it to use JSONP
Because browser
<script>tags can load scripts from different domains, it is one way to work around cross-domain issues, with little worry about cross-browser support. It does pose some potential Cross-Site-Scripting Issues (I recommend reading the wiki page I linked above) that you should be aware of.Make JSONP API calls is super easy if you use
jQuery, but it’s still simple enough to do with strict javascript by dynamically injecting the<script>tags yourself, setting thesrcattribute to your API endpoint, and creating your own callback function that is invoked once the call is successful.Modify your server endpoint to take a
callbackparameter. Wrap your json response with the callback.e.g. (not real code)
If you’d rather not support JSONP, you can enable Cross Origin Resource Sharing (CORS). Both iOS and Android webbrowsers support it. In order to add support for CORS, you’ll need to modify your endpoint to send the appropriate headers: