【问题标题】:How to display API data using Ajax?如何使用 Ajax 显示 API 数据?
【发布时间】:2020-02-28 17:26:54
【问题描述】:

我希望能够使用下面代码中的 API 以格式化的方式显示数据,例如这个示例。

Job Title: Agricultural and Related Trades

Percentage of Occupancies in Area: 15.41%

您可以找到我在下面显示数据的糟糕尝试。我对 Ajax、jQuery、JavaScript 等非常陌生。

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(function() {
        $.ajax({
        url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
        type: "get",
        dataType: "json",
        success: function(data) {
            console.log(data[0].area);

            outputString= data[0].description.percentage;
            var paragraph = $("<p />", {
                text: outputString
            });

            $("body").append(paragraph);
        }
        });
    });
</script>

【问题讨论】:

标签: javascript jquery html ajax api


【解决方案1】:

这样的东西很可能是你想要的:

<script>
$(function() {
    $.ajax({
        url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
        type: "get",
        dataType: "json",
        success: function(data) {
            data.jobsBreakdown.forEach(function(job) {
                var job_text = "Job Title: " + job.description;
                var percentage_text = "Percentage of Occupancies in Area: " + job.percentage.toFixed(2) + "%"
                $("body").append("<div style='margin-bottom: 10px;'><div>" + job_text + "</div><div>" + percentage_text + "</div></div>")
            })
        }
    });
});
</script>

【讨论】:

    【解决方案2】:

    您可以使用string templates 来创建您的段落内容。 使用&lt;br /&gt; HTML 元素在段落中创建一个新行。

    let data = [{
      area: 'Agricultural and Related Trades',
      percentage: 15.41
    }]
    
    var paragraph = document.createElement('p');
    paragraph.innerHTML = `Job Title: ${data[0].area}<br/>
    Percentage of Occupancies in Area: ${data[0].percentage}%"`;
    document.body.appendChild(paragraph);

    【讨论】:

      【解决方案3】:
      • 您需要定义一个函数来呈现描述和百分比的单个项目。
      • 解析百分比,可以使用Number object
      • 当您从 Ajax 取回数据时,您需要循环这些项目并将它们中的每一个传递给您之前定义的渲染函数(这里我使用了forEach)。
      • 通常,根据经验,您必须将代码拆分为具有单一职责的函数。

      function renderItem(itemData) {
        const title = $('<p/>').text('Job Title: ' + itemData.description);
         const percentage = $('<p/>').text('Percentage of Occupancies in Area: '+ new Number(itemData.percentage).toFixed(2) + '%');
         const item = $('<li/>').append(title, percentage);
        $('#result').append(item);
      }
      
      $(function() {
       $.ajax({
       url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
       type: "get",
       dataType: "json",
       success: function(data) {
        data.jobsBreakdown.forEach(renderItem);
       }
       });
      });
      Job Title: Agricultural and Related Trades
      
      Percentage of Occupancies in Area: 15.41%
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <ul id="result"></ul>

      【讨论】:

        【解决方案4】:

        成功执行 GET 请求后,您将在 data 变量中获得响应,现在您可以运行 for 循环来填充您的预期结果 'HTML' TEXT 而不是你可以将它附加到你的 HTML 正文中

        我在这里使用了 JavaScript toFixed() Method 只保留两位小数

           $(function() {
                $.ajax({
                url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
               method: "GET",
                dataType: "json",
                success: function(data) {
                    var str = "";          
                   for(var i= 0; i < data.jobsBreakdown.length; i++){
        
                     str +='Job Title : '+data.jobsBreakdown[i].description+' and Related Trades <br> Percentage of Occupancies in Area : '+data.jobsBreakdown[i].percentage.toPrecision(2)+'% <br><br>';
                   }
                  $("body").html(str);
                }
                });
            });
         
         <!DOCTYPE html>
        <html>
        <head>
        <title>Page Title</title>
         <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        </head>
        <body>
        
        <h1>This is a Heading</h1>
        <p>This is a paragraph.</p>
        
        </body>
        </html>

        【讨论】:

        • 非常感谢!这非常有效,您的演示和解释质量一流。
        • 很高兴知道它对你有帮助@user12200628
        猜你喜欢
        • 2018-10-29
        • 2015-10-02
        • 2018-09-14
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        相关资源
        最近更新 更多