简体   繁体   English

如何从多个URL获取JSON数据

[英]How to get JSON data from multiple URLs

I need to get data from two URLs and fetch them to a single table. 我需要从两个URL中获取数据并将其提取到单个表中。 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: 您可以将更新版本的请求与fetch使用,并使用Promise.allawait (本机支持):

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. deferred.done()-添加要解析Deferred对象时调用的处理程序。

You don't see the response may be because one of the promises is rejected. 您看不到响应可能是因为其中一项承诺被拒绝了。 Try using deferred.then() 尝试使用deferred.then()

Or loop result1 and result2 separately 或分别循环result1和result2

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

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

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