▍程式碼
<!-- 編輯視窗 -->
<!-- 編輯視窗 -->
<div>
<div class="insert-bg hide"></div>
<div id="insert-window" class="hide">
<form method="GET" action="/update_question">
<span id="insert-w-close">
<svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path>
</svg>
</span>
<div class="insert-field">
<label class="insert-t">題目:</label>
<input type="text" class="insert-input" id="insert-question">
</div>
<div class="insert-field">
<label class="insert-t">選項:</label>
<textarea class="insert-input" id="insert-option"></textarea>
</div>
<div class="insert-field">
<label class="insert-t">答案:</label>
<input type="text" class="insert-input" id="insert-answer">
</div>
<div class="insert-field">
<label class="insert-t">來源書籍:</label>
<input type="text" class="insert-input" id="insert-sbook">
</div>
<div class="insert-field">
<label class="insert-t">頁次:</label>
<input type="text" class="insert-input" id="insert-page">
</div>
<div class="insert-field">
<label class="insert-t">來源檔案:</label>
<input type="text" class="insert-input" id="insert-sfile">
</div>
<button id="update-submit">確定</button>
</form>
</div>
</div>
<script>
// 開啟編輯視窗
$(".all_questions, #insert-w-close").on('click', function edit() {
$("#insert-window, .insert-bg").toggleClass("hide");
if ($(".insert-bg").attr("style") !== "pointer-events: auto;") {
$(".insert-bg, #insert-window").attr("style", "pointer-events: auto;");
}
else {
$(".insert-bg, #insert-window").attr("style", "");
}
if (!questionData || Object.keys(questionData).length === 0) {
console.warn("警告:無法從題目元素中提取數據,無法編輯。");
return;
}
currentEditingQuestion = JSON.parse(JSON.stringify(questionData));
// 加索引
currentEditingQuestion.original_index = index;
});
$("#update-submit").on('click', function saveChanges() {
let modifiedQuestions = getModifiedDataFromUI(); // 假設這個函數能返回一個新的題目列表
if (!modifiedQuestions || modifiedQuestions.length === 0) {
alert("沒有要儲存的數據。");
return;
}
// 2. 使用 $.ajax 將數據發送給後端
$.ajax({
url: '/update_questions',
type: 'POST',
// 將 JavaScript 物件轉換為 JSON 字符串發送
data: JSON.stringify(modifiedQuestions),
// 告訴伺服器我們發送的是 JSON 格式
contentType: 'application/json',
success: function (response) {
alert(response.message);
console.log("更新成功:", response);
// 可以在這裡刷新頁面或更新 UI
},
error: function (jqXHR, textStatus, errorThrown) {
const errorMsg = jqXHR.responseJSON ? jqXHR.responseJSON.error : '未知錯誤';
console.error("更新失敗:", errorMsg);
alert("更新失敗: " + errorMsg);
}
});
});
</script>