如何将 API 请求中的 JSON 获取到页面的 javascript 中

How do I get the JSON from an API request into my page's javascript?

本文关键字:javascript 获取 JSON API 请求      更新时间:2023-09-26

我正在尝试使用Web api在JavaScript中返回JSON文件。使用 Alchemy API,调用将指向以下 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

这将对 macrumors 文章进行情绪分析。但是,我不确定如何将JSON文件实际获取到javascript中。有人知道怎么做吗?

您正在访问的 URL 似乎返回 JSON,因此请使用 ajax get请求

使用 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);
  }
);

不能对客户端的其他域使用 AJAX 调用,因为浏览器出于安全原因会阻止此操作。如果必须执行跨域调用,则需要使用 JSONP。下面是代码的一个工作示例(sans jQuery!)的粘贴:http://pastebin.com/8vN8LqWW

因此,虽然可以在客户端处理所有这些问题,但不建议这样做。如果只是为了测试或个人项目,那很好,但如果你真的把它推送到公共网络,你将把你的秘密API密钥暴露给全世界。最好在服务器端进行API调用,即使用Node.js,Python,Ruby或类似的东西。AlchemyAPI有几个SDK来帮助你入门。

顺便说一句,为了披露,我为 AlchemyAPI 工作。

我看不到史蒂夫共享的粘贴,并在jQuery中编写了以下内容(我知道没有提到jQuery,但我认为这可以很容易地适应没有jQuery的JS):

$.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);
  }
});

希望这对寻找它的人:)有所帮助!我还在这里创建了一个要点:https://gist.github.com/Wysie/32b2f7276e4bd6acb66a