How to get JSON data from multiple URLs

I need to get data from two URLs and extract it into one table. How can i do this? Can someone help me how to do this? Thanks in advance.

What I tried is here. But he does not show anything.

var url1 = 'http://localhost:8080/WebService/rest/payment/get/payment';
var url2 = 'http://localhost:8080/WebService/rest/orderdetails/get/all';
$(document).ready(function() {
  $.when(
    $.getJSON(url1),
    $.getJSON(url2)).done(function(result1, result2) {
    var table = $("#oTable");
    $.each(result1, result2, function(i, value) {
      table.append('<tr><td>1</td><td class="txt-oflo">' + value.payment + '</td><td>' + value.username + '</td><td class="txt-oflo">' + value.date + '</td><td><span class="text-success">' + value.price + '</span></td><td><a href=""><button class="btn btn-success">Place</button></a>  <a href=""><button class="btn btn-danger">Cancel</button></a></td></tr>');
    });
  });
});
+4
source share
2 answers

You can use a more modern version of queries with fetchand use Promise.alland await, supported initially:

const url1 = 'http://localhost:8080/WebService/rest/payment/get/payment';
const url2 = 'http://localhost:8080/WebService/rest/orderdetails/get/all';
const fetchJSON = url => fetch(url).then(response => response.json())

$(document).ready(async () => {
  const [result1, result2] = await Promise.all(fetchJSON(url1), fetchJSON(url2));
  const results = [...result1, ...result2];
  const table = $("#oTable");
  results.forEach((value) => (
      table.append('<tr><td>1</td><td class="txt-oflo">' + value.payment + '</td><td>' + value.username + '</td><td class="txt-oflo">' + value.date + '</td><td><span class="text-success">' + value.price + '</span></td><td><a href=""><button class="btn btn-success">Place</button></a>  <a href=""><button class="btn btn-danger">Cancel</button></a></td></tr>')
  ));
});
+2
source

deferred.done () - Add handlers that will be called when the Deferred object resolves.

You do not see that the answer may be caused by the fact that one of the promises is rejected. Try using deferred .then ()

Or the result of cycle 1 and result2 separately

$.each(result1, function(i, value) {
  table.append('<tr><td>1</td><td class="txt-oflo">' + value.payment + '</td><td>' + value.username + '</td><td class="txt-oflo">' + value.date + '</td><td><span class="text-success">' + value.price + '</span></td><td><a href=""><button class="btn btn-success">Place</button></a>  <a href=""><button class="btn btn-danger">Cancel</button></a></td></tr>');
});
+1
source

Source: https://habr.com/ru/post/1696093/


All Articles