简体   繁体   English

从Web API提取和读取JSON数据

[英]Extract and read JSON Data from web API

What I'm working on is providing 1 line instant definitions of terms and perhaps one line answers to few logical questions. 我正在研究的是提供1行术语的即时定义,也许一行可以回答几个逻辑问题。 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. 假设用户输入“ JavaScript”,并且JavaScript访问URL https://api.duckduckgo.com/?q=JavaScript&format=json&pretty=1 ,则获得“定义”项(请查看API链接以了解,定义位于第一行本身)并显示其“定义”值,并用所需的数据提醒用户。

Anyways my code currently is: 无论如何,我的代码当前是:

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

Please note that I've not put in the required JavaScript/jQuery code as I'm confused with this. 请注意,由于我对此感到困惑,所以我没有输入所需的JavaScript / jQuery代码。 Thank you :) 谢谢 :)

Because this is a cross-domain request you can only do this with a proxy or with JSONP. 因为这是一个跨域请求,所以您只能使用代理或JSONP来执行此操作。 Fortunately DuckDuckGo supports JSONP , so you just need to ensure that you add a callback parameter to the URL request like: 幸运的是, DuckDuckGo支持JSONP ,因此您只需要确保向URL请求中添加一个回调参数即可,例如:

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

... or use the appropriate jsonp parameter with jQuery's ajax method, something like: ...或将适当的jsonp参数与jQuery的ajax方法配合使用,例如:

$('#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);
    });
  }

});

Use jQuery.ajax() to talk to the remote service. 使用jQuery.ajax()与远程服务对话。 url should be https://api.duckduckgo.com . url应为https://api.duckduckgo.com type should be GET . type应该是GET data should be: data应为:

var data = { q:'JavaScript', format:'json', pretty:1 };

jQuery will then compile everything into an AJAX request, send it to the server. jQuery然后将所有内容编译成AJAX请求,并将其发送到服务器。 Pass a function as success so you can do something with the result: 将函数作为success传递,这样您就可以对结果做一些事情:

$.ajax({
    url: "https://api.duckduckgo.com",
    type: "GET",
    data: { q:'JavaScript', format:'json', pretty:1 },
    success: function(data) {  $('#output').html(data); }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM