Reputation: 2037
I read this article and this. How can I adopt using script tags to query cross domain for the following:
var nytimes_api = 'http://api.nytimes.com/svc/semantic/v2/concept/article/2010/10/06/business/media/06tribune.json?&fields=article_list&api-key=4949d84e6ed8e55dbd7352d88da21f6d:9:65735612'; // returns JSON
// code accessing nytimes_url
// and retrieving data from it
Thanks.
Upvotes: 1
Views: 1670
Reputation: 208
In order to use script tags in the way you describe, the API you are requesting data from needs to support JSONP. More specifically, it needs to support passing a parameter such as ?callback=myFunction
and then wrapping its output in that function so that you can execute the data as a script.
For example, if /api.json
returned something like so:
{'name': 'Bob'}
You'd need /api.json?callback=myFunction
to return:
myFunction({'name': 'Bob'});
You could then use something like jQuery's $.getJSON
function to handle the script creation for you.
Unfortunately, it doesn't look like the New York Times API currently supports JSONP though there is an open request for it.
In order to use this API without JSONP, you're going to need some server-side component to make the request for you.
Upvotes: 0
Reputation: 707376
Research JSONP and see if the NYTimes API supports it and how you can use it.
Reference articles:
http://en.wikipedia.org/wiki/JSONP
http://remysharp.com/2007/10/08/what-is-jsonp/
Plenty more references with a Google search for JSONP.
In a nutshell, JSONP makes a script request to the remote site using a custom URL with parameters in it. Typically one of the parameters is a javascript function name of yours that the returned javascript will call when it has it's data. So, you make the script request of the remote site. The remote server gets the script request. It parses out the parameters from the URL to see what you're asking it to do. One of those parameters is a javascript function name. The remote server then returns some javascript. Part of that javascript is typically both the data that you requested and a call to the javascript function name that you specified in the URL. When the browser executes that returned javascript, your function call gets called with the requested data as a parameter.
The details of how the data is returned are up to the implementor of the API and would be something you would have to get from the NYTimes API description.
You can only use this JSONP technique with an API that explicitly supports it.
Upvotes: 2