How do I get the JSON from an API request into my

2019-08-08 21:12发布

问题:

I'm trying to use a web api to return a JSON file in JavaScript. Using the Alchemy API, the call would be to the following URL:

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

This would run sentiment analysis on a macrumors article. However, I am unsure as to how to actually get the JSON file into javascript. Does anybody know how?

回答1:

The URL you're accessing appears to return JSON, so use an ajax get request

With jQuery.get():

var Url = '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);
  }
);


回答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.



回答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
    }
    else if (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