【问题标题】:fetch api css loader获取 api css 加载器
【发布时间】:2018-06-20 12:13:32
【问题描述】:

我正在使用 fetch API 来访问我在线开发和托管的 REST API。但是当从数据库中检索数据(>60 行)以显示在页面的某个部分中时,显示我使用 HTML 和 CSS 设置样式的数据大约需要 3-5 秒。

我的问题是如何在显示实际数据之前实现一个 CSS 预加载器来加载。还有我怎么知道数据已经显示出来了。

下面是我的部分代码。

// Front end
frontend.html

<table>
<caption>User requests</caption>
<thead class="table-head">
<tr>
    <th scope="col">Request Id</th>
    <th scope="col">User ID</th>
    <th scope="col">Brand</th>
        <th scope="col">Type</th>
 </tr>
 </thead>
 <tbody id="tablebody">

  <div class="loader" id="loader"></div>

  </tbody>
     </table> 





// file.js
fetch(url, { 
method: 'GET',
headers: {'Authorization': 'Bearer ' +token}
}).then(response =>{ 
// Redirect the user to the login page
// If the user is not an admin
if(response.status === 401) {
    window.location.replace('./Index.html');
}
return response.json()
})
.then((data) => {  
let completedata = data.allRequests;
if(completedata) {
    completedata.forEach((item) => {
        timeStamp = new Date(item.createdon);
        dateTime = timeStamp.toDateString();
        theOutput +=`<tr id="listofrequests"><a href=""></a><td data- 
label="Request Id">${item.id}</td> </a>
        <td data-label="Brand">${item.userid}</td>
        <td data-label="Brand">${item.brand}</td>
        <td data-label="Type">${item.other}</td>
        <td data-label="Status">${item.name}</td>
        <td data-label="Status"><a href="./Request-status.html" class="btn 
view-detail" id="${item.id}" onClick="adminviewonerequest(this.id)">view</a> 
</td>
<td data-label="Cancel"><button class="danger" id="${item.id}" 
name="${item.name}" onClick="return cancelrequest(this.id, this.name)"><i 
class="fa fa-trash"> Cancel Request</i></button></td>
      </tr>`;
    });
}
else {
    toastr.warning(data.message);
}

document.getElementById('tablebody').innerHTML = theOutput;           
})
.catch(err => console.log(err));

【问题讨论】:

  • file.js 是 node.js 应用程序的入口点还是普通的 java 脚本文件?
  • 不是入口点。这是一个普通的javascript文件

标签: node.js fetch-api preloader


【解决方案1】:

使用那些已经实现的负载微调器How to make a loading spinner in html

然后,在你的html代码中添加&lt;div id="loading" class="loader"&gt;&lt;/div&gt;,这使得加载器默认显示

并使用 fetch :

fetch(YouUrl)
.then(res => {
    if(res == 404){
        // To hide the loader when the error is happen , There is no need to use loader 
        // Show some toaster notification for the user or sweet alert 
        document.getElementById("loading").style.display = 'none';   
    }
})
.then(json => {
    // Here is your data so you need to hide the loader 
    document.getElementById("loading").style.display = 'none';   
});

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2018-03-03
    • 1970-01-01
    • 2016-08-10
    • 2022-12-11
    • 2016-03-06
    • 2021-08-26
    • 2018-07-15
    • 2023-01-09
    相关资源
    最近更新 更多