How Do I Get The Json From An Api Request Into My Page's Javascript?
Solution 1:
The URL you're accessing appears to return JSON, so use an ajax get
request
With jQuery.get():
varUrl = 'http://access.alchemyapi.com/calls/url/URLGetTextSentiment?url=http%3A%2F%2Fwww.macrumors.com%2F2013%2F11%2F05%2Fapple-releases-itunes-11-1-3-with-equalizer-and-performance-improvements%2F&apikey=[secret]&outputMode=json'
$.get(
Url,
function(data, status, xhr){
alert(data);
}
);
Solution 2:
You can't use AJAX calls to other domains on the client side since browsers block this for security reasons. If you must do a cross domain call, you'll need to use JSONP. Here's a pastebin of a working example (sans jQuery!) of your code: http://pastebin.com/8vN8LqWW
So while it's possible to handle this all on the client side, it's not recommended. If it's just for testing or a personal project that's fine, but if you actually push this out to the public web you will be exposing your secret API key to the world. It's much better to make the API calls on the server side, i.e. using Node.js, Python, Ruby or similar. AlchemyAPI has several SDKs to help you get started.
BTW, for disclosure, I work for AlchemyAPI.
Solution 3:
I couldn't see the pastebin that was shared by Steve and wrote the following in jQuery (I know no jQuery was mentioned, but I think this can be easily adapted to JS without jQuery):
$.ajax({
url: 'https://access.alchemyapi.com/calls/text/TextGetTextSentiment',
dataType: 'jsonp',
jsonp: 'jsonp',
type: "post",
data: { apikey: 'APIKEYHERE', text: streamText, outputMode: 'json' },
success: function(res){
if (res["status"] === "OK") {
//Do something good
}
elseif (res["status"] === "ERROR") {
//Do something bad
}
},
error: function(jqxhr) {
//console.log(jqxhr);
}
});
Hope this helps the people looking for it :)! I've also created a gist here: https://gist.github.com/Wysie/32b2f7276e4bd6acb66a
Post a Comment for "How Do I Get The Json From An Api Request Into My Page's Javascript?"