简体   繁体   中英

How to get JSON data from multiple URLs

I need to get data from two URLs and fetch them to a single table. How can I do that? Can anybody help me how to do that? Thanks in advance.

What I tried is here. But it shows nothing.

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

You can use the more modern version of requests with fetch and use Promise.all and await , supported natively:

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

deferred.done() - Add handlers to be called when the Deferred object is resolved.

You don't see the response may be because one of the promises is rejected. Try using deferred.then()

Or loop result1 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>');
});

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