我正在尝试使用javascript和html从在线MongoDb数据库中获取数据。但它不能正常工作。也使用jquery库
<div>
<input type="submit" value="GET DATA FROM API" id="getAPI">
<div id="result" ></div>
<div ><h2>Input Form</h2></div>
<form id="postData" >
</form>
</div>
<!-- javascript part -->
<script>
document.getElementById('getAPI').addEventListener('click', getAPI);
function getAPI() {
fetch('http://localhost:3000/api/seller')
.then((res) => { return res.json() })
.then((data) => {
let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
data.forEach((seller) => {
const {id, name, email} = seller
result +=
`<div>
<h5> User ID: ${id} </h5>
<ul>
<li> User Full Name : ${name}</li>
<li> User Email : ${email} </li>
</ul>
</div>`;
document.getElementById('result').innerHTML = result;
});
})
}
</script>
<script src="jquery-3.3.1.min.js" type="text/javascript"></script>
答案 0 :(得分:-1)
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => {
return res.json();
})
.then(data => {
let result = `<h2> Random User Info From Jsonplaceholder API</h2>`;
data.forEach(seller => {
const {
id,
name,
email
} = seller;
result += `<div>
<h5> User ID: ${id} </h5>
<ul>
<li> User Full Name : ${name}</li>
<li> User Email : ${email} </li>
</ul>
</div>`;
document.getElementById("app").innerHTML = result;
});
});
<div id="app"></div>
您的前端效果很好。我在您的代码中替换了api网址,一切正常。它可能在后端。您是否检查了从服务器获得的状态代码?