从WEB API获取JSON数据并打印为HTML

时间:2019-09-09 11:03:35

标签: html json

我的主要网站有一个门户网站(类似于登录页面)。 我有类似的东西:subdomain.mywebsite.com/portal/statistics可打印:

{"onlineUsers":"53","registeredUsers":"31608","connectedTodayOnWebsite":212,"connectedLastMonth":"6729"}

在我的.html目标网页上有以下内容:

<div class="row counters">

          <div class="col-lg-3 col-6 text-center">
            <span data-toggle="counter-up" id="online">274</span>
          </div>

          <div class="col-lg-3 col-6 text-center">
            <span data-toggle="counter-up" id="registered">421</span>
          </div>

          <div class="col-lg-3 col-6 text-center">
            <span data-toggle="counter-up" id="connectedtoday">1,364</span>
          </div>

          <div class="col-lg-3 col-6 text-center">
            <span data-toggle="counter-up" id="connectedlastmonth">18</span>
          </div>

        </div>

如何将API中的数字打印到该div / span中?我想我应该使用一些AJAX,但我真的不明白。

2 个答案:

答案 0 :(得分:1)

当然,您必须从选择的API服务器端点获取数据。首先,您将有2个不同的部分,一个是HTML,另一个是纯Javascript。另外,您可以使用一些JS库,但是在该示例中,我们将看到一个纯JS示例。

HTML非常接近,例如我们可以做到:

<div class="row counters">

  <div class="col-lg-3 col-6 text-center">
    <span data-toggle="counter-up" id="online">Loading...</span>
  </div>

  <div class="col-lg-3 col-6 text-center">
    <span data-toggle="counter-up" id="registered">Loading...</span>
  </div>

  <div class="col-lg-3 col-6 text-center">
    <span data-toggle="counter-up" id="connectedtoday">Loading...</span>
  </div>

  <div class="col-lg-3 col-6 text-center">
    <span data-toggle="counter-up" id="connectedlastmonth">Loading...</span>
  </div>

</div>

默认情况下,数据尚未到达,我们可以向用户显示“正在加载”。另一方面,我们有一个Javascript代码。 Javascript的第一部分是打开与服务器API端点的连接:

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'HERE_IS_YOUR_SERVER_API_ENDPOINT', true)

request.onload = function () {
  // Begin accessing JSON data here, MAGIC IS HERE
}

// Send request
request.send()

现在,我们将使用JSON响应。请记住,服务器管理员的工作是使服务器响应以JSON格式而不是XML或其他方式进行。

// Begin accessing JSON data here
var data = JSON.parse(this.response)

// Now you can use your data, for example:
setDataValues(data)

function setDataValues (data) {
   document.getElementById('online').innerHTML = data.onlineUsers
   // Do the same with the others values
}

答案 1 :(得分:-1)

= -4142