javascript中的fetch()不是';t从JSON生成表
我一直在阅读关于使用fetch的文档,但显然我并不完全理解某些东西。我希望它获取数据,然后将数据发送到一个函数,该函数将在我在html文档中创建的某些字段下创建一个表。我认为问题在于这一行javascript中的fetch()不是';t从JSON生成表,javascript,html,fetch,Javascript,Html,Fetch,我一直在阅读关于使用fetch的文档,但显然我并不完全理解某些东西。我希望它获取数据,然后将数据发送到一个函数,该函数将在我在html文档中创建的某些字段下创建一个表。我认为问题在于这一行 var div = document.getElementById('div1'); 特别是“div1”部分。div1是否必须是已创建的表?我试图在css文件中添加一个表,但我要么做得不正确,要么与问题无关 据我所知,我完全遵循了文档。也许我错过了什么 这是我的html <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>
<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>
我是皮克特
添加客户
添加客户
名称
地址
城市
陈述
拉链
拯救
取消
正在加载客户。。。
设置超时(()=>{
获取客户();
}, 2000);
var客户=[];
var selectedCustomer=null;
var theMap;
地理编码器;
//地理编码
// https://developers.google.com/maps/documentation/javascript/geocoding
函数addCustomersToMap(){
用于(客户的风险值c){
addCustomerToMap(c);
}
}
函数latLangToLatLngLiteral(latLang){
var-latLangArray=latLang.split(“:”);
var lat=parseFloat(latLangArray[0]);
var lng=parseFloat(latLangArray[1]);
返回{
拉特:拉特,
液化天然气:液化天然气
};
}
函数addCustomerToMap(客户){
var latLang=customer.latLang;
如果(!拉特朗){
log('No latLang for:',customer.name);
返回;
}
customer.mapMarker=addPinToMap(latlangtolatngliteral(latLang));
}
函数addPinToMap(latLng){
var marker=new google.maps.marker({
地图:主题地图,
职位:latLng
});
google.maps.event.addListener(标记'click',函数(){
地图设置缩放(9);
theMap.setCenter(marker.getPosition());
});
返回标记;
}
函数updateCustomers(新客户){
console.log('Draw customers!');
客户=新客户;
重画CustomerDiv();
设置超时(()=>{
addCustomersToMap();
}, 1000);
}
函数fetchCustomers(){
让url为空http://cs1.utm.edu/~bbradley/map1/customers1.json';
fetch(url)//调用fetch函数,将API的url作为参数传递
.then((resp)=>resp.json())//将数据转换为json
.then(功能(数据){
log('Got customers!');
更新用户(数据);
})
.catch(函数(错误){
//这是在服务器返回任何错误时运行代码的地方
log('获取客户时出错!',错误);
警报(“获取客户时出错!”);
});
}
异步函数zoomMapToMarker(标记器){
如果(!标记){
console.log('No marker!');
返回;
}
地图设置缩放(5);
等待睡眠(500);
theMap.setCenter(marker.getPosition());
等待睡眠(1000);
地图设置缩放(9);
}
功能展示客户(cNum){
设c=客户[cNum];
selectedCustomer=c;
动物标记(c.mapMarker);
重新绘制的PICDIV(选定的客户);
}
函数showAddDialog(){
const modal=document.querySelector('.my modal');
modal.showModal();
}
函数closeDialog(){
const modal=document.querySelector('.my modal');
modal.close();
}
函数closeAndSave(){
让customer={};
customer.name=document.getElementById('nameField')。值;
customer.address=document.getElementById('addressField')。值;
customer.cityStateZip=document.getElementById('cityField').value+,'+document.getElementById('stateField').value+''+document.getElementById('zipField').value;
closeDialog();
addCustomerToTop(客户);
}
函数addCustomerToTop(c){
客户=[c,…客户];
重画CustomerDiv();
设置超时(()=>{
地理编码客户(c,(loc)=>{
国际单项体育联合会(loc){
c、 latLang=loc.lat()+“:”+loc.lng();
addCustomerToMap(c);
重画CustomerDiv();
动物标记(c.mapMarker);
}
});
}, 1000);
}
/*将获得客户的loc/latlng,然后使用loc调用回调*/
函数geocodeCustomer(客户,回调){
var address=customer.address+“”+customer.cityStateZip;
地理编码地址(地址,回调);
}
/*将获取地址的loc/latlng,然后使用loc调用回调*/
函数geocodeAddress(地址,回调){
geocoder.geocode({
“地址”:地址
},功能(结果、状态){
如果(状态=‘正常’){
var loc=results[0]。geometry.location;
回拨(loc);
}否则{
console.log('地理代码由于以下原因未成功:'+状态);
回调(空);
}
});
}
功能addToCustomers(名称、地址、cityStateZip){
变量aObject={
姓名:姓名,,
地址:地址:,
cityStateZip:cityStateZip
}
customers.push(aObject);
}
函数重绘picdiv(selectedCustomer){
设e=document.getElementById('pictDiv');
log('Debug redrawPicDiv here');
如果(!selectedCustomer){
e、 innerHTML='没有选定的用户';
返回;
}如果(!selectedCustomer.image),则为else{
e、 innerHTML='无图像';
}否则{
e、 innerHTML=`;
}
e、 innerHTML+=`${selectedCustomer.name}`;
e、 innerHTML+=`${selectedCustomer.address}`;
e、 innerHTML+=`${selectedCustomer.cityStateZip}`;
}
函数重画CustomerDiv(){
var div=document.getElementById('div1');
var newHTML=`
<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>
<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>