What would that code look like?
views:
119answers:
6You can use JSONP. in jQuery, try getJSON: http://api.jquery.com/jQuery.getJSON/
Have a look at this question - it's about jQuery but the answer is about javascript in general: Why cant I load an external resource from jQuery load method?
That other domain/server needs to support JSONP, which basically wraps the JSON in a callback.
In jQuery, the call would look like this:
$.getJSON(
'http://otherdomain.com/api/whatever?callback=?',
{ key: 'value', otherkey: true },
function(data){
//handle response
}
);
The actual response from the other server (if you looked at what was actually being sent) would look like this:
// With this url:
http://domain.com/api/method?callback=the_callback_function_name
// The response would look like this:
the_callback_function_name({ "json": "data here"});
The jQuery getJSON method automatically handles JSONP when you supply the extra callback=?
. Just keep in mind some sites using different names like json_callback=?
. The important part is that you include it as part of the URL and don't try to add callback: '?'
to the data
part of the getJSON
function.
Only via JSONP. Whether you use jQuery or some other framework, it boils down to a script block like this:
<script type="text/javascript" src="http://path.to/your/javascript"></script>
The <script>
block is immune from cross-domain restrictions. The caveat is that the service should support JSONP as well. If the script returns a JSON object like this:
{a: 0, b: 1}
The object will be evaluated but nothing happens. But JSONP services accept a callback function name something like this
<script type="text/javascript" src="http://path.to/your/javascript?callback=yourCallbackFunction"></script>
and wrap the data as a parameter to your callback like this:
yourCallbackFunction({a: 0, b: 1});
So that the function is called when the script is evaluated.
Instead you should use a local proxy. Set up a asp.net/php page that will load the remote page on the back end and then use ajax to load the proxy page.