извлечь json в таблицу (конечная точка) - PullRequest
1 голос
/ 01 апреля 2020

я новичок в javascript, пытаюсь учиться каждый день, здесь я пытаюсь получить json данные из URL с конечными точками, по какой-то причине данные не приходят в «таблицу», я вижу их в console.log но не на столе. мои json данные выглядят так:

{
  "id": "145127236",
  "mygoals": "success",
  "future": "high",
  "dole": {
    "Key": "fhd699f"
  }
}

и мой код выглядит так:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <style>
    </style>
	
</head>
<body>

<div class="container">
    <table class="table table-stripped"> 
	    <thead>
		   <tr> 
		       <th> emp id</th>
			   <th> emp mygoals</th>
 		       <th> emp future</th>

		   </tr> 
		</thead>
	
	
      <tbody id="data" >
 </tbody>
  </table
</div>


    <script>
  fetch("https://sp*****.com/get/henkilot/98765432/sijoitus",
              {
              method: "GET",
              headers: {
                 "x-api-key": "p*****w"
              }
            }
          ).then(res =>{ 

        res.json().then(
		data=> {
		console.log(data);
		if(data.length > 0){
		var temp ="";
		
		data.forEach((u) =>{
		      temp +="<tr>";
			  temp += "<td>"+u.id+"</td>";
			  temp += "<td>"+u.mygoals+"</td>";
			  temp += "<td>"+u.future+"</td></tr>";

		})
		       document.getElementById("data").innerHTML = temp
		}
		}
	  )
    }
  )
 .catch(err => {
          console.log("ERROR: " + err);
        });
    </script>

</body>
</html> 

Ответы [ 2 ]

2 голосов
/ 01 апреля 2020

Кажется, данные JSON, которые вы написали в вопросе, не являются массивом, поэтому нет необходимости перебирать данные. Один из вариантов - удалить forEach или исправить ответ конечной точки, если у вас есть к нему доступ.

Этот код считает, что конечная точка не отвечает массивом:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <style>
    </style>
	
</head>
<body>

<div class="container">
    <table class="table table-stripped"> 
	    <thead>
		   <tr> 
		       <th> emp id</th>
			   <th> emp mygoals</th>
 		       <th> emp future</th>

		   </tr> 
		</thead>
	
	
      <tbody id="data" >
 </tbody>
  </table>
</div>


    <script>
  fetch("https://asdasd.free.beeceptor.com/a",
              {
              method: "GET",
              headers: {
                 "x-api-key": "p*****w"
              }
            }
          ).then(res =>{ 

        res.json().then(
		data=> {
		console.log(data);
		var temp ="";
		
	      temp +="<tr>";
		  temp += "<td>"+data.id+"</td>";
		  temp += "<td>"+data.mygoals+"</td>";
		  temp += "<td>"+data.future+"</td></tr>";

		   document.getElementById("data").innerHTML = temp
		}
	  )
    }
  )
 .catch(err => {
          console.log("ERROR: " + err);
        });
    </script>

</body>
</html> 
0 голосов
/ 01 апреля 2020

Ваши брекеты безумны
попробуйте это:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
    <table class="table table-stripped"> 
      <thead>
        <tr> 
          <th> emp id </th>
          <th> emp mygoals </th>
          <th> emp future </th>
        </tr> 
      </thead>
      <tbody id="data"></tbody>
    </table>
  </div>

<script>
  const tableData = document.getElementById("data")
    ;
  fetch("https://sp*****.com/get/henkilot/98765432/sijoitus",
    { method: "GET"
    , headers: { "x-api-key": "p*****w" }
    })
  .then(res=>res.json())
  .then(data=>
    {
    console.log(data)
    data.forEach(u=>
      {
      let newRow = tableData.insertRow()
      newRow.insertCell().textContent = u.id
      newRow.insertCell().textContent = u.mygoals
      newRow.insertCell().textContent = u.future
      })
    })
  .catch(err => console.log("ERROR: " + err) );
</script>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...