首页 > 解决方案 > 如何使用 Ajax 显示 API 数据?

问题描述

我希望能够使用下面代码中的 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>

标签: javascriptjqueryhtmlajaxapi

解决方案


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

我这里使用了 JavaScript toFixed()方法,只保留两位小数

   $(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>


推荐阅读