Vue 3如何获取问卷输入值并组装为JSON对象发送到Django后端
完整修改方案
1. 调整组件脚本逻辑
首先修正数据绑定逻辑,新增作答存储对象,初始化题目默认值:
<script> export default { data() { return { sections: data.sections, // 新增存储作答的对象,结构和你要求的输出完全一致 responses: {} } }, props:[ 'sectionStart', 'sectionEnd' ], created() { // 初始化所有题目的作答默认值 this.sections.forEach(section => { section.questions.forEach(question => { if (question.type === 'Single Choice') { // 单选题默认空值 this.$set(this.responses, question.id, null) } else if (question.type === 'Multiple Choice') { // 多选题默认空数组 this.$set(this.responses, question.id, []) } }) }) }, methods: { // 新增提交方法 async submitSurvey() { try { const res = await fetch('/你的后端接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value // Django需要的CSRF令牌 }, body: JSON.stringify({ responses: this.responses }) }) const result = await res.json() // 处理提交成功逻辑 console.log('提交成功', result) } catch (err) { // 处理提交错误逻辑 console.error('提交失败', err) } } } }; </script>
2. 修正模板绑定
修改单选、多选组件的绑定规则,删除无效代码:
<template> <div> <div v-for="section in sections.slice(sectionStart, sectionEnd)" :key="section.id"> <div v-for="question in section.questions" :key="question.id"> <!-- Single Choice --> <div v-show="question.type === 'Single Choice'" :id="question.id"> <p class="py-4 font-medium leading-8">{{ question.question_text }}</p> <!-- 删除原来无效的hidden input --> <div class="flex py-1" v-for="choice in question.choices" :key="choice.id"> <!-- 修正v-model绑定,设置value为选项id --> <input class="h-5 w-5" type="radio" :name="question.id" v-model="responses[question.id]" :value="choice.id" :id="choice.id"/> <label class="ml-3" :for="choice.id">{{ choice.text }}</label> </div> </div> <!-- Multiple choice --> <div v-show="question.type === 'Multiple Choice'" :id="question.id"> <p class="py-4 font-medium leading-8">{{ question.question_text }}</p> <div class="flex py-1" v-for="choice in question.choices" :key="choice.id"> <!-- 修正name为题目id,绑定v-model和value --> <input type="checkbox" class="h-6 w-6" :name="question.id" v-model="responses[question.id]" :value="choice.id" :id="choice.id"> <label :for="choice.id" class="ml-3">{{ choice.text }}</label> </div> </div> </div> </div> <!-- 新增提交按钮触发提交方法 --> <button @click="submitSurvey" class="mt-6 px-4 py-2 bg-blue-500 text-white rounded">提交问卷</button> </div> </template>
3. Django后端接收示例
视图中直接解析JSON数据即可:
import json from django.http import JsonResponse from django.views.decorators.http import require_http_methods @require_http_methods(["POST"]) def submit_survey(request): data = json.loads(request.body) responses = data.get('responses', {}) # 这里处理作答存储逻辑 for question_id, answer in responses.items(): # 按需处理单选/多选答案 pass return JsonResponse({'status': 'success'})
responses对象的结构和你要求的输出格式完全一致:单选题对应选中的选项ID值,多选题对应选中的选项ID数组。
内容的提问来源于stack exchange,提问作者Mahdi Jafari
相关产品推荐
相关产品推荐

