创建动态html并在其中显示json值

时间:2018-09-20 06:37:25

标签: jquery html css json ajax

我已经调用了ajax api调用,我得到了json格式的响应。我想在屏幕上用html元素显示每个值。我已经实现了这一点,但是它无法根据需要创建动态设计。如果没有数据响应,我还要显示一条消息(“无可用数据”)。这是我的工作HTML和JSON示例。 需要显示如下

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
    <div class="portlet light bg-inverse tripcontainer">
        <div id="container">
            <div class="col-md-4 driver">
                <div>
                    <label class="header">Driver Details</label>
                </div>
                <div>
                    <label>Name:</label>
                    <span class="dname"></span>
                </div>
                <div>
                    <label>Vehicle No:</label>
                    <span class="dvehicle"></span>
                </div>
                <div>
                    <label>Mobile No:</label>
                    <span class="dmob"></span>
                </div>
                <div>
                    <label>Email:</label>
                    <span class="demail"></span>
                </div>
                <div>
                    <label>Start Location:</label>
                    <span class="dstart"></span>
                </div>
                <div>
                    <label>Lat:</label>
                    <span class="dlat"></span>
                </div>
                <div>
                    <label>Long:</label>
                    <span class="dlong"></span>
                </div>
                <div>
                    <label>End Location:</label>
                    <span class="dend"></span>
                </div>
                <div>
                    <label>Lat:</label>
                    <span class="dselat"></span>
                </div>
                <div>
                    <label>Long:</label>
                    <span class="dselong"></span>
                </div>
                <div>
                    <label>Booked Seats:</label>
                    <span class="dseat"></span>
                </div>
                <div>
                    <label>Start Time:</label>
                    <span class="dstarttime"></span>
                </div>
                <div>
                    <label>Route ID:</label>
                    <span class="droute"></span>
                </div>
                <div>
                    <label>Distance:</label>
                    <span class="ddistance"></span>KM</div>
            </div>
            <div class="col-md-8 passanger">
                <div>
                    <label class="header">Passanger Details</label>
                </div>
                <div>
                    <label>Name:</label>
                    <span class="pname"></span>
                </div>
                <div>
                    <label>Mobile No:</label>
                    <span class="pmob"></span>
                </div>
                <div>
                    <label>Email:</label>
                    <span class="pemail"></span>
                </div>
                <div>
                    <label>Start Location:</label>
                    <span class="pstart"></span>
                </div>
                <div>
                    <label>Lat:</label>
                    <span class="pslat"></span>
                </div>
                <div>
                    <label>Long:</label>
                    <span class="pelong"></span>
                </div>
                <div>
                    <label>End Location:</label>
                    <span class="pend"></span>
                </div>
                <div>
                    <label>Lat:</label>
                    <span class="pelat"></span>
                </div>
                <div>
                    <label>Long:</label>
                    <span class="pelong"></span>
                </div>
                <div>
                    <label>Booked Seats:</label>
                    <span class="pseat"></span>
                </div>
                <div>
                    <label>Start Time:</label>
                    <span class="pstarttie"></span>
                </div>
                <div>
                    <label>End Time:</label>
                    <span class="pendtime"></span>
                </div>
                <div>
                    <label>Distance:</label>
                    <span class="pdistance"></span>KM</div>
            </div>
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:0)

如果我理解得很好,您想填写每个信息 因此,使用javascript可以解析:

var parsedResponse = JSON.parse(ajaxesponse);
if(parsedResponse.length = 0){
   console.log('No data');
}else{
   var keys = Object.keys(parsedResponse[0]);
   //parsedResponse[0] for driver data
   for(var i = 0; i < keys.length ; i++){
      //The best thing to do is to change your class name and name it the same way as your keys in the response object
      $("."+keys[i]).html(parsedResponse[0][keys[i]]);
   }
}

和您的html: 代替

<div>
   <label>Email:</label>
   <span class="demail"></span>
</div>

你有类似的东西

<div>
   <label>Email:</label>
   <span class="email"></span>
</div>

答案 1 :(得分:0)

要使其动态化,您可以按照以下步骤操作

1。像这样为驱动程序分配值

$('.dname').html(driver_data[0].employeename);

2。像这样为乘客分配值

$('.pname').html(driver_data[0].passenger_data[0].employeename);

3。遍历您的结果(应该是第一个)

for (i = 0; i < result.length; i++) { 
// your assignments here
}

在这里,我已经在此 fiddle

中解析并附加了值

这是追加后的样子

[![在此处输入图片描述] [2]] [2]

注意:

  1. 我为驾驶员和乘客添加了一些字段,您应该对其进行遍历并使其符合您的意愿。

  2. 您不需要创建静态HTML,而是可以从jquery本身执行此操作。这样您可以减少代码量。

更新:

OP希望如何遍历结果并修复其中的数据。

这里是updated fiddle,可以动态迭代

这是它的样子

[![输出] [4]] [4]

$(document).ready(function() {
    $.get("http://www.mocky.io/v2/5ba349e82f000054009685b0", function(data, status) {
        var output = '';
        for (i = 0; i < data.length; i++) {
            var driverHtml = '<div class="col-md-4 driver"><div><label class="header">Driver Details</label></div><div><label>Name:</label><span class="dname">' + data[i].employeename + '</span></div>';
            var passengerHtml = '<div class="col-md-8 passenger"><div><label class="header">Passenger Details</label></div><div><label>Name:</label><span class="pname">' + data[i].passenger_data[0].employeename + '</span></div><hr>';
            output += driverHtml + passengerHtml;
        }
        $('#container').html(output);
    });
});

更新说明:

我已使用Mocky作为数据来模拟real time output like this

我还动态创建了HTML,仅填写了几个字段。您也可以填写其余字段。

希望这对您有所帮助。

答案 2 :(得分:0)

有几种方法可以在HTML中填充JSON数据,即Ajax,getJSON,Fetch,JavaScript(纯),XMLHttpRequest。

这是下面使用fetch()方法的示例。您可以根据自己的需要对其进行修改:

<div>
    <table>
        <tbody id="my-list">
            <tr>
                <th>Field 01</th>
                <th>Field 02</th>
                <th>Field 03</th>
                <th>Field 04</th>
                <th>Field 05</th>
            </tr>
        </tbody>
    </table>
</div>


<script>

$(function () {
    const url = 'https://jsonplaceholder.typicode.com/todos';
    fetch(url, { /* other parameters */ })
        .then(resp => resp.json())
        .then(data => { // Your code for handling the data you get from the API
            renderData(data);
        })
        .catch(function (error) { // This is where you run code if the server returns any errors
            console.log('There has been a problem with your fetch operation: ', error.message);
        });
});


function renderList(data) {
    var list = "";
    $.each(data, function (index) {
        href = "https://jsonplaceholder.typicode.com/todos?id=" + data[index].Id;
        list += "<tr>";
        list += "<td>" + data[index].Field01 + "</td>";
        list += "<td>" + data[index].Field02 + "</td>";
        list += "<td>" + data[index].Field03 + "</td>";
        list += "<td>" + data[index].Field04 + "</td>";
        list += "<td>" + data[index].Field05 + "</td>";
        list += "</tr>";
    })
    $("#my-list").append(list);
}

</script>

希望这对您有帮助...