[英]How to correctly code an interchange data between server-side and client-side using JavaScript?
我在 web 應用程序上工作,需要在 HTML 頁面中合並可編輯表。 發現了很棒的 JS 工具“Tabulator”,但是,我缺乏從服務器到客戶端和返回的數據傳輸的基本基礎知識。 好吧,進入正題。
在服務器端:
app.js
在客戶端:
stat.html
到嵌入兩個 Tabulator 的表table.js
=== 階段 1. 從服務器向客戶端發送數據 ===
步驟 1. app.js
從 Mongo DB 中提取數據並將其發送到table.js
//=== render stat.html page ===//
router.get('/stat', (req,res)=>{
res.render('stat');
});
//=== pull user data from mongo and send it to table.js ===//
router.get('/stat', (req,res) => {
User.find({}, (err, users) => {
if (err) throw err;
res.send(users);
});
});
//=== pull resource data from mongoand send it to table.js ===//
router.get('/stat', (req,res) => {
Resource.find({}, (err, resources) => {
if (err) throw err;
res.send(resources);
});
});
這里我有幾個問題:
Collection.find
中的 output 采用 JSON 格式,這正是 Tabulator 所需要的。 在將其發送到客戶端之前,我是否需要對其進行操作? 例如使用JSON.stringify
/stat/user
和/stat/resource
但是如何觸發它們? 步驟 2. 在客戶端table.js
文件接收數據並將其提供給 Tabulator 表。 Tabulator 有自己的選項來請求遠程數據ajaxURL
//setup user table
var table = new Tabulator('#user-table',{
ajaxURL:"stat/user",
});
//setup resource table
var table = new Tabulator('#resource-table',{
ajaxURL:"stat/resource",
});
問題:
ajaxURL
如何在table.js
中讀取數據? 我嘗試獲取 API 但沒有成功。 在table.js
中獲取請求
fetch('/stat/user', {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(users)
})
.then(response => response.json())
.then(function(response) {
if (response.ok) {
console.log('got data: ', response.users);
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
第 2 階段旨在將數據從客戶端發送回服務器。 但我認為這已經是壓倒性的,也許最好把這部分放在一邊。
我知道互聯網上有大量的文章,StackOverflow 中關於這個主題的問題,並且閱讀了很多但仍然沒有掌握它,所以請不要建議像 MDN 手冊這樣的東西。
我會非常感謝任何幫助。
自己整理的。 特別感謝@jonrsharpe。
如果有人在這個問題上需要幫助,我很樂意提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.