0

今天我用ajax获取外部api值并显示在html中,但是从ajax中获取值是成功的,但是我不知道如何显示它,所以我留下一个问题。

下面的代码被称为来自外部 api 的 json 值。

{
    "addr": "address",
    "code": "38807050",
    "created_at": "2020/03/28 13:15:00", 
    "lat": x axis, 
    "lng": y axis, 
    "name": "store name", 
    "remain_stat": "1", 
    "stock_at": "2020/03/28 11:37:00", 
    "type": "01"
 }

我想让从外部 api 调用的 json 值如下图所示。我怎样才能得到那里调用的价值?

在此处输入图像描述

           <div class="row pt-4 px-5 moreBox" style="display: none;">
            <div class="pb-5 col-md-5">
              <iframe width="100%" height="300" src="https://maps.google.com/maps?q=New%20York&amp;z=14&amp;output=embed" scrolling="no" frameborder="0"></iframe></div>
            <div class="col-md-6">
              <h1 class="">store name</h1>
              <p class="lead">address</p>
              <h5 class="">created at</h5>
              <h6 class="">stock_at</h6>
            </div>
          </div>
4

1 回答 1

0

嗨,您需要制作一个 javascript 文件,然后动态处理来自 .js 文件的 html。我使用点击侦听器实现此功能,您可以根据您的选择进行设置。我认为以下代码将帮助您理解重点。

例如在 Html 文件中

            <div class="col-md-6" id="datatoload">
            </div>

在脚本文件中

document.getElementById('datatoload').addEventListener('load', loadData);
function loadData() {
 // Create the object
 const xhr = new XMLHttpRequest();

 // Open the connection
 xhr.open('GET', '<URL>', true);

 // Execute the function
 xhr.onload = function() {
      if(this.status === 200) {
           // Get the response as an Object
           const data = JSON.parse( this.responseText );

           let output = '';
           data.forEach(function(d) {
                output += `

                          <h1 class="">${d.name}</h1>
                          <p class="lead"> ${d.addr}</p>
                          <h5 class="">${d.created_at}</h5>
                          <h6 class=""> ${d.stock_at}</h6>

                `;
           });

           document.getElementById('datatoload').innerHTML = output;

      }
 }

 // Send the request
 xhr.send();

}

您可以简单地尝试此代码

于 2020-03-28T04:44:20.933 回答