我的應用程式包含一個計分表網格,其中每個單元格代表一個學生在一個主題中的分數。教師可以在每個單元格中輸入分數,然后單擊提交按鈕一次發送所有分數。
這是我現在擁有的 ejs 表單:
記分表.ejs
<tbody>
<% students.forEach((student, i) => { %>
<tr>
<td class="student-cell right">
<%= student.last_name %>, <%= student.first_name[0] %>
</td>
<% topics.forEach(topic=> { %>
<td class="score-cell center">
<input type="text" class="score-input" name="scores_<%= student.id %>_<%= topic.id %>">
</td>
<% }); %>
</tr>
<% }) %>
</tbody>
這種形式產生一個看起來像這樣的 req.body:
scores_1_2: '75',
scores_1_3: '92',
scores_1_4: '100',
scores_1_5: '100',
scores_1_6: '',
scores_2_1: '65',
scores_2_2: '60',
scores_2_3: '50',
scores_2_4: '35',
我正在嘗試獲取這些資料并將其轉換為 Postgresql 查詢(或多個查詢)。
例如,行 score_2_4: '35' 將變為
UPDATE scores SET points = 35 WHERE student_id = 2 AND topic_id = 4
分數表是一個多對多連接表,用于連接學生和主題。
我懷疑我的表格還有一些作業要做。我可能沒有以理想的方式發送這些資料。這是迄今為止我最好的解決方案,包括 student_id 和 topic_id 以及老師的分數輸入。
如果這種方法是可以接受的,那么我還需要有關如何將所有這些資料轉換為更新陳述句的提示。
我正在使用當前版本的 postgresql、nodejs、express、ejs 和 node-postgres 包。
提前感謝您的任何見解。
uj5u.com熱心網友回復:
到目前為止,這是我最好的解決方案,包括
student_id和topic_id老師的分數輸入。
是的,沒關系。您只需scores_${student_id}_${topic_id}將服務器上的格式決議回您期望的資料結構。
不過,更習慣的編碼是使用括號表示法而不是下劃線。許多application/x-www-form-urlencodedPOST 正文的決議器可以自動將其轉換為嵌套物件,請參閱例如Can not post the nested object json to node express body parser和How to get nested form data in express.js? .
<input type="text" class="score-input" name="scores[<%= student.id %>][<%= topic.id %>]">
我還需要有關如何將所有這些資料轉換為更新陳述句的提示。
為簡單起見,使用多個UPDATE陳述句:
const { scores } = req.body;
for (const studentId in scores) {
const studentScores = scores[studentId];
for (const topicId in studentScores) {
const points = studentScores[topicId];
// TODO: check for permission (current user is a teacher who teaches the topic to the student)
await pgClient.query(
'UPDATE scores SET points = $3 WHERE student_id = $1 AND topic_id = $2',
[studentId, topicId, points]
);
}
}
您可能希望輸入一parseInt兩個對 進行適當的輸入驗證studentId,topicId并且points如果您需要它們是整數而不是字串;否則 postgres 會拋出例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/498451.html
