从Web API提取和读取JSON数据 [英] Extract and read JSON Data from web API

查看:396
本文介绍了从Web API提取和读取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究的是提供1行术语的即时定义,也许一行可以回答一些逻辑问题.假设用户输入"JavaScript",并且JavaScript访问URL https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1 ,获取项目定义"(请查看API链接以了解,定义位于第一行本身)并显示其值定义并警告用户所需的数据.

What I'm working on is providing 1 line instant definitions of terms and perhaps one line answers to few logical questions. Suppose a user inputs "JavaScript" and JavaScript visits the url https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1, gets the item "Definition" (Look at the API link to understand, Definition is in the first line itself) and displays its value of Definition and alert the user with the required data.

无论如何,我当前的代码是:

Anyways my code currently is:

<html>
<head>
<title>Hi</title></head>
<body>
<input id="ddgAPI"><button>Search</button>
<div id="output"></div>
</body>
</html> 

请注意,由于我对此感到困惑,因此我没有输入所需的JavaScript/jQuery代码.谢谢:)

Please note that I've not put in the required JavaScript/jQuery code as I'm confused with this. Thank you :)

推荐答案

由于这是一个跨域请求,因此只能使用代理或JSONP进行.幸运的是 DuckDuckGo支持JSONP ,因此您只需要确保在URL请求中添加一个回调参数即可,例如:

Because this is a cross-domain request you can only do this with a proxy or with JSONP. Fortunately DuckDuckGo supports JSONP, so you just need to ensure that you add a callback parameter to the URL request like:

https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1&callback=jsonp

...或在jQuery的ajax方法中使用适当的jsonp参数,例如:

... or use the appropriate jsonp parameter with jQuery's ajax method, something like:

$('#ddgAPI').on('keyup', function(e) {

  if (e.which === '13') {
    $.ajax({
      type: 'GET',
      url: 'https://api.duckduckgo.com/',
      data: { q: $(this).val(), format: 'json', pretty: 1 },
      jsonpCallback: 'jsonp',
      dataType: 'jsonp'
    }).then(function (data) {
      console.log(data);
    });
  }

});

这篇关于从Web API提取和读取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆