From 7193b9a000e3912a8c31435d68f814068645db9a Mon Sep 17 00:00:00 2001 From: Cai Date: Mon, 5 Jan 2026 15:50:51 +0800 Subject: [PATCH] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E5=A4=8D=E5=89=8D?= =?UTF-8?q?=E7=AB=AFthis=20undefined=E5=AF=BC=E8=87=B4=E7=9A=84=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E9=80=89=E8=AF=BE=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Html/apps/static/js/index.js | 60 +++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/Html/apps/static/js/index.js b/Html/apps/static/js/index.js index badb381..a200494 100644 --- a/Html/apps/static/js/index.js +++ b/Html/apps/static/js/index.js @@ -1,41 +1,53 @@ -function show_books(courses_data, user_selected_courses){ +function show_books(courses_data, user_selected_courses) { console.log(courses_data) console.log(user_selected_courses) } -function show_course_details(course_id){ - window.location.href = '/course/' + course_id +function show_course_details(course_id) { + window.location.href = '/course/' + course_id } -function on_click_select_course(event){ +function on_click_select_course(event) { event.stopPropagation(); // 阻止事件冒泡 - const courseId = event.currentTarget.getAttribute('data-course-id'); - if (event.currentTarget.classList.contains("selected-button")) {alert('课程已选择'); return;} + const button = event.currentTarget; + const courseId = button.getAttribute('data-course-id'); + if (!courseId) { alert('缺少课程ID'); return; } + if (button.classList.contains("selected-button")) { alert('课程已选择'); return; } + if (button.disabled) { return; } + button.disabled = true; fetch(`/select_course`, { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-CSRFToken': '{{ csrf_token() }}' // 如果使用 CSRF 保护 }, body: JSON.stringify({ course_id: courseId }) }) - .then(response => response.json()) - .then(data => { - if (data.success) { - // 更新按钮样式或显示消息 - this.classList.remove('select-button'); - this.classList.add('selected-button'); - this.textContent = '已选择'; + .then(async (response) => { + let data = null; + try { + data = await response.json(); + } catch (_) { + } + if (!response.ok) { + throw new Error(data?.message || `请求失败(${response.status})`); + } + return data; + }) + .then((data) => { + if (!data?.success) { + throw new Error(data?.message || '选择课程失败'); + } + button.classList.remove('select-button'); + button.classList.add('selected-button'); + button.textContent = '已选课'; alert('选择课程成功'); - } else { - alert('选择课程失败'); - } - }) - .catch(error => { - console.error('Error:', error); - alert('选择课程失败'); - }); + }) + .catch(error => { + console.error('Error:', error); + alert(error?.message || '选择课程失败'); + button.disabled = false; + }); } -document.addEventListener('DOMContentLoaded', function() { +document.addEventListener('DOMContentLoaded', function () { -}); \ No newline at end of file +});