首页 > 解决方案 > javascript中的fetch()不是从JSON制作表格

问题描述

我一直在阅读有关使用 fetch 的文档,但显然我并没有完全理解某些内容。我希望它获取然后将数据发送到一个函数,该函数将在我在 html 文档中创建的某些字段下创建一个表。我认为问题在于这条线......

 var div = document.getElementById('div1');

特别是“div1”部分。div1 是否必须是已创建的表?我尝试尝试将表格添加到我的 css 文件中,但要么做错了,要么与问题无关。

据我所知,我完全遵循文档。也许我错过了什么?

这是我的html。


<html>
    <body>

        <div>
            <div id="myMap" style="float:left;width:calc( 100% - 302px);height:400px;"></div>
            <div id="pictDiv" style="width:300px;height:400px;float:right;border:1px solid black;">
                PICT HERE</div>
        </div>


        <hr>

        <button onclick="showAddDialog()">Add Customer</button>

    <dialog class="my-modal">
                <p>Add Customer</p>
                <label for="nameField">Name</label><input id=nameField><br>
                <label for="addressField">Address</label><input id=addressField><br>
                <label for="cityField">City</label><input id=cityField><br>
                <label for="stateField">State</label><input id=stateField size=2> &nbsp;
                <label for="zipField">Zip</label><input id=zipField><br>

                <br>
                <button onclick="closeAndSave()">Save</button>
                <button onclick="close()">Cancel</button>
            </dialog>

            <div id=div1>LOADING CUSTOMERS...</div>

            <script>
                setTimeout(() => {
                    fetchCustomers();
                }, 2000);
            </script>

                <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDWJQkyTlID7v5wSSceXr21aKCNQELLWV0&callback=myMap"></script>

    <!--JQuery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <!-- DataTables-->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
</body>
</html>
<script>
var customers = [];
var selectedCustomer = null;
var theMap;
var theGeocoder;



// geocoding
// https://developers.google.com/maps/documentation/javascript/geocoding

function addCustomersToMap() {
    for (var c of customers) {
        addCustomerToMap(c);
    }
}

function latLangToLatLngLiteral(latLang) {
    var latLangArray = latLang.split(':');
    var lat = parseFloat(latLangArray[0]);
    var lng = parseFloat(latLangArray[1]);
    return {
        lat: lat,
        lng: lng
    };
}

function addCustomerToMap(customer) {
    var latLang = customer.latLang;
    if (!latLang) {
        console.log('No latLang for: ', customer.name);
        return;
    }
    customer.mapMarker = addPinToMap(latLangToLatLngLiteral(latLang));
}

function addPinToMap(latLng) {
    var marker = new google.maps.Marker({
        map: theMap,
        position: latLng
    });

    google.maps.event.addListener(marker, 'click', function() {
        theMap.setZoom(9);
        theMap.setCenter(marker.getPosition());
    });

    return marker;
}

function updateCustomers(newCustomers) {
    console.log('Draw customers!');
    customers = newCustomers;
    redrawCustomerDiv();
    setTimeout(() => {
        addCustomersToMap();
    }, 1000);
}


function fetchCustomers() {
    let url = 'http://cs1.utm.edu/~bbradley/map1/customers1.json';
    fetch(url) // Call the fetch function passing the url of the API as a parameter
        .then((resp) => resp.json()) // Transform the data into json
        .then(function(data) {
            console.log('Got customers!');
            updateCustomers(data);

        })
        .catch(function(error) {
            // This is where you run code if the server returns any errors
            console.log('Error while fetching customers!', error);
            alert('Error while fetching customers!');
        });
}


async function zoomMapToMarker(marker) {
    if (!marker) {
        console.log('No marker!');
        return;
    }
    theMap.setZoom(5);
    await sleep(500);
    theMap.setCenter(marker.getPosition());
    await sleep(1000);
    theMap.setZoom(9);
}


function showCustomer(cNum) {
    let c = customers[cNum];
    selectedCustomer = c;
    zoomMapToMarker(c.mapMarker);
    redrawPicDiv(selectedCustomer);
}

function showAddDialog() {
    const modal = document.querySelector('.my-modal');
    modal.showModal();
}

function closeDialog() {
    const modal = document.querySelector('.my-modal');
    modal.close();
}

function closeAndSave() {
    let customer = {};
    customer.name = document.getElementById('nameField').value;
    customer.address = document.getElementById('addressField').value;
    customer.cityStateZip = document.getElementById('cityField').value + ', ' + document.getElementById('stateField').value + ' ' + document.getElementById('zipField').value;
    closeDialog();
    addCustomerToTop(customer);
}

function addCustomerToTop(c) {
    customers = [c, ...customers];
    redrawCustomerDiv();

    setTimeout(() => {
        geocodeCustomer(c, (loc) => {
            if (loc) {
                c.latLang = loc.lat() + ":" + loc.lng();
                addCustomerToMap(c);
                redrawCustomerDiv();
                zoomMapToMarker(c.mapMarker);
            }
        });
    }, 1000);
}

/* will get loc/latlng of customer and then call the callBack with loc */
function geocodeCustomer(customer, callBack) {
    var address = customer.address + " " + customer.cityStateZip;
    geocodeAddress(address, callBack);
}

/* will get the loc/latlng of an address and then call the callBack with loc */
function geocodeAddress(address, callBack) {

    theGeocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == 'OK') {
            var loc = results[0].geometry.location;
            callBack(loc);
        } else {
            console.log('Geocode was not successful for the following reason: ' + status);
            callBack(null);
        }
    });
}

function addToCustomers(name, address, cityStateZip) {
    var aObject = {
        name: name,
        address: address,
        cityStateZip: cityStateZip
    }
    customers.push(aObject);
}

function redrawPicDiv(selectedCustomer) {
    let e = document.getElementById('pictDiv');
    console.log('Debug redrawPicDiv here');
    if (!selectedCustomer) {
        e.innerHTML = '<h1>No selected user</h1>';
        return;
    } else if (!selectedCustomer.image) {
        e.innerHTML = '<h2>No Image</h2>';
    } else {
        e.innerHTML = `<img style='max-width:290;' src='${selectedCustomer.image}'>`;
    }

    e.innerHTML += `<div>${selectedCustomer.name}</div>`;
    e.innerHTML += `<div>${selectedCustomer.address}</div>`;
    e.innerHTML += `<div>${selectedCustomer.cityStateZip}</div>`;
}

function redrawCustomerDiv() {

    var div = document.getElementById('div1');

    var newHTML = `<table border=1 id='my_table'>
                    <thead>
                    <tr>
                    <th>Cmd</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>CityStateZip</th>
                    <th>Lat Lang</th>
                    </tr>
                    </thead>
                    <tbody>`;

    let count = 0;
    for (c of customers) {

        newHTML += `
            <tr>
            <td><button onclick='showCustomer(${count})'>Show</button></td>
            <td> ${c.name} </td>
            <td> ${c.address} </td>
            <td> ${c.cityStateZip} </td>
            <td> ${c.latLang ? c.latLang : '?'} </td>
            </tr>
        `;
        count++;
    }

    newHTML += '</tbody></table>';

    div.innerHTML = newHTML;

    $('#my_table').DataTable();

}

function sleep(ms) { // https://www.sitepoint.com/delay-sleep-pause-wait/
    return new Promise(resolve => setTimeout(resolve, ms));
}
</script>


表是否必须已经创建?我迷路了。

标签: javascripthtmlfetch

解决方案


您是否添加了 jquery 数据表插件?也缺少 AddCustomersToMap 方法。

    <html>
<body>
<dialog class="my-modal">
            <p>Add Customer</p>
            <label for="nameField">Name</label><input id=nameField><br>
            <label for="addressField">Address</label><input id=addressField><br>
            <label for="cityField">City</label><input id=cityField><br>
            <label for="stateField">State</label><input id=stateField size=2> &nbsp;
            <label for="zipField">Zip</label><input id=zipField><br>

            <br>
            <button onclick="closeAndSave()">Save</button>
            <button onclick="close()">Cancel</button>
        </dialog>

        <div id=div1>LOADING CUSTOMERS...</div>




        <script>
            setTimeout(() => {
                fetchCustomers();
            }, 2000);
            function fetchCustomers() {
    let url = 'http://cs1.utm.edu/~bbradley/map1/customers1.json';
    fetch(url) // Call the fetch function passing the url of the API as a parameter
        .then((resp) => resp.json()) // Transform the data into json
        .then(function(data) {
            console.log('Got customers!');
            updateCustomers(data);

        })
        .catch(function(error) {
            // This is where you run code if the server returns any errors
            console.log('Error while fetching customers!', error);
            alert('Error while fetching customers!');
        });
}

function updateCustomers(newCustomers) {
    console.log('Draw customers!');
    customers = newCustomers;
    redrawCustomerDiv();
    setTimeout(() => {
        addCustomersToMap();
    }, 1000);
}

// Here's where the problem lies

function redrawCustomerDiv() {

    var div = document.getElementById('div1');

    var newHTML = `<table border=1 id='my_table'>
                    <thead>
                    <tr>
                    <th>Cmd</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>CityStateZip</th>
                    <th>Lat Lang</th>
                    </tr>
                    </thead>
                    <tbody>`;

    let count = 0;
    for (c of customers) {

        newHTML += `
            <tr>
            <td><button onclick='showCustomer(${count})'>Show</button></td>
            <td> ${c.name} </td>
            <td> ${c.address} </td>
            <td> ${c.cityStateZip} </td>
            <td> ${c.latLang ? c.latLang : '?'} </td>
            </tr>
        `;
        count++;
    }

    newHTML += '</tbody></table>';

    div.innerHTML = newHTML;

    //$('#my_table').DataTable();

}
</script>
</body>
</html>

推荐阅读