Page({ data: { question: {}, // 当前题目 options: [], // 格式化后的选项 selectedIndex: null, // 用户选中的选项索引 score: 0, // 用户得分 showResult: false, // 是否显示结果弹窗 isCorrect: false, // 答案是否正确 resultText: "", // 结果提示文本 explanation: "", // 答案解析 loading: false // 加载状态 }, onLoad() { this.loadQuestion(); }, // 从API加载随机题目 loadQuestion() { this.setData({ loading: true }); wx.request({ url: 'http://127.0.0.1:8000/api/questions/random/', method: 'GET', success: (res) => { if (res.statusCode === 200) { this.processQuestionData(res.data); } else { this.handleError('题目加载失败'); } }, fail: (err) => { this.handleError('网络请求失败'); this.useLocalData(); // 失败时使用本地测试数据 }, complete: () => { this.setData({ loading: false }); } }); }, // 处理API返回的题目数据 processQuestionData(apiData) { // 确保数据完整性 if (!apiData.choices || apiData.choices.length === 0) { this.handleError('题目数据不完整'); return this.useLocalData(); } this.setData({ question: apiData, explanation: apiData.explanation || "暂无解析" }); // 格式化选项为A/B/C/D const options = apiData.choices.map((choice, index) => ({ id: choice.id, key: String.fromCharCode(65 + index), // A, B, C... value: choice.text, isCorrect: choice.is_correct })); this.setData({ options, selectedIndex: null, showResult: false }); }, // 用户选择选项 selectOption(e) { this.setData({ selectedIndex: e.currentTarget.dataset.index }); }, // 提交答案 submitAnswer() { if (this.data.selectedIndex === null) { wx.showToast({ title: '请先选择答案', icon: 'none' }); return; } const selectedOption = this.data.options[this.data.selectedIndex]; const isCorrect = selectedOption.isCorrect; const scoreChange = isCorrect ? 2 : -1; this.setData({ showResult: true, isCorrect, score: Math.max(0, this.data.score + scoreChange), resultText: isCorrect ? '回答正确!+2分' : `回答错误!正确答案:${this.getCorrectAnswer()}` }); }, // 获取正确答案文本 getCorrectAnswer() { const correctOption = this.data.options.find(opt => opt.isCorrect); return correctOption ? `${correctOption.key}. ${correctOption.value}` : ''; }, // 下一题 nextQuestion() { this.loadQuestion(); }, // 错误处理 handleError(msg) { console.error(msg); wx.showToast({ title: msg, icon: 'none' }); }, onShow(){ this.recordFeatureUsage('quiz-main'); }, recordFeatureUsage(featureName) { const app = getApp(); console.log('发送的Token:', app.globalData.userInfo.token); console.log('发送的featureName:', featureName); wx.request({ url: 'http://127.0.0.1:8000/api/record-usage/', method: 'POST', header: { 'Authorization': `Token ${app.globalData.userInfo.token}`, 'Content-Type': 'application/json' // 确保这个请求头存在 }, data: JSON.stringify({ // 关键修改:必须使用JSON.stringify feature_name: featureName // 参数名必须与后端一致 }), success: (res) => { console.log('行为记录响应:', res.data); }, fail: (err) => { console.error('请求失败:', err); } }); }, })