如何使用Ajax显示API数据?

Eua*_*M28 2 html javascript api ajax jquery

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

Job Title: Agricultural and Related Trades

Percentage of Occupancies in Area: 15.41%
Run Code Online (Sandbox Code Playgroud)

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

Job Title: Agricultural and Related Trades

Percentage of Occupancies in Area: 15.41%
Run Code Online (Sandbox Code Playgroud)

Sha*_*ain 7

成功执行 GET 请求后,您将在数据变量处收到响应,现在您可以运行 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);
        }
        });
    });
Run Code Online (Sandbox Code Playgroud)
 
 <!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>
Run Code Online (Sandbox Code Playgroud)