简体   繁体   中英

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

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

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

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

});

Use jQuery.ajax() to talk to the remote service. url should be https://api.duckduckgo.com . type should be GET . data should be:

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

jQuery will then compile everything into an AJAX request, send it to the server. Pass a function as success so you can do something with the result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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