Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

});

Solution 2:

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

vardata = { 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); }
});

Post a Comment for "Extract And Read Json Data From Web Api"