Noodles
Noodles

Reputation: 23

How to get json data coming from another domain?

I want to use the google images api. In the past when I worked with json I simply used the ajax function to get the json from my own server. But now I will be getting it from an external domain:

https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy monkey&v=1.0

Obviously I can't load this using js since its not from an internal url. So in these cases how does one work with json data. Are you supposed to load it via CURL using a server side script or is there another way?

Upvotes: 2

Views: 5977

Answers (2)

alex
alex

Reputation: 490413

You can make use of JSONP by adding a callback GET param.

https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=hello

Then you can request it with jQuery's $.getJSON().

$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(response) {
    console.log(response.responseData);
});

jsFiddle.

Upvotes: 3

zakdances
zakdances

Reputation: 23715

You must use Cross Origin Resource Sharing (CORS http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing)

It's not as complicated as it sounds...simply set your request headers appropriately...in Python it would look like:

    self.response.headers.add_header('Access-Control-Allow-Origin', '*');
    self.response.headers.add_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    self.response.headers.add_header('Access-Control-Allow-Headers', 'X-Requested-With');
    self.response.headers.add_header('Access-Control-Max-Age', '86400');

Upvotes: 1

Related Questions