You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript捕获网页用户选中的所有选项并传递至Django后端?

实现网页表单数据提交到Django后端并触发流程

前端实现(HTML + 可选异步提交)

先写基础HTML表单,确保每个表单元素带name属性(后端靠这个取值),同时添加Django要求的CSRF令牌:

<form method="POST" action="{% url 'submit_form' %}">
    {% csrf_token %}
    
    <!-- 文本输入框 -->
    <div>
        <label>输入内容:</label>
        <input type="text" name="user_input" required>
    </div>
    
    <!-- 单选按钮组 -->
    <div>
        <p>选择操作选项:</p>
        <input type="radio" name="selected_option" value="option1" required>
        <label>选项1</label>
        
        <input type="radio" name="selected_option" value="option2">
        <label>选项2</label>
    </div>
    
    <button type="submit">保存并触发流程</button>
</form>
  • {% url 'submit_form' %}是Django的URL反向解析,需要提前在urls.py配置对应路由
  • {% csrf_token %}必须添加,否则Django会拒绝POST请求

如果需要不刷新页面提交,用JavaScript实现异步提交(以Fetch API为例):

document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault(); // 阻止默认页面跳转
    
    const formData = new FormData(this);
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    
    fetch(this.action, {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrfToken
        },
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        console.log('流程已触发:', data);
        // 这里可以添加用户提示,比如弹出成功消息
    })
    .catch(err => console.error('提交失败:', err));
});

Django后端实现(视图 + 路由)

1. 配置路由(urls.py)

给提交接口配置URL:

from django.urls import path
from . import views

urlpatterns = [
    # 表单提交接口
    path('submit-choice/', views.submit_choice_view, name='submit_form'),
    # 可选:提交成功后的跳转页面
    path('success/', views.success_view, name='success_page'),
]

2. 编写视图函数(views.py)

接收表单数据,验证后触发对应流程:

from django.shortcuts import render, redirect
from django.http import JsonResponse

def submit_choice_view(request):
    if request.method == 'POST':
        # 从POST请求中获取数据
        user_input = request.POST.get('user_input')
        selected_option = request.POST.get('selected_option')
        
        # 基于用户选择触发对应流程
        if selected_option == 'option1':
            run_option1_process(user_input)
        elif selected_option == 'option2':
            run_option2_process(user_input)
        
        # 处理响应:异步请求返回JSON,普通请求跳转页面
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({'status': 'ok', 'msg': '流程执行成功'})
        return redirect('success_page')
    
    # GET请求返回表单页面
    return render(request, 'choice_form.html')

# 示例流程函数,根据实际需求替换
def run_option1_process(input_text):
    # 比如保存到数据库、调用外部API、触发Celery任务等
    print(f"执行选项1流程,用户输入:{input_text}")

def run_option2_process(input_text):
    print(f"执行选项2流程,用户输入:{input_text}")

def success_view(request):
    return render(request, 'success.html')

进阶:用Django Form做数据验证

如果需要规范的字段验证,定义Form类:

from django import forms

class UserChoiceForm(forms.Form):
    user_input = forms.CharField(max_length=200, label='输入内容', required=True)
    selected_option = forms.ChoiceField(
        choices=[('option1', '选项1'), ('option2', '选项2')],
        label='操作选项',
        required=True
    )

视图中使用这个Form:

def submit_choice_view(request):
    if request.method == 'POST':
        form = UserChoiceForm(request.POST)
        if form.is_valid():
            # 从cleaned_data取验证后的数据
            user_input = form.cleaned_data['user_input']
            selected_option = form.cleaned_data['selected_option']
            # 触发流程...
            # 响应逻辑...
    else:
        form = UserChoiceForm()
    return render(request, 'choice_form.html', {'form': form})

前端模板可直接用Form渲染简化代码:

<form method="POST" action="{% url 'submit_form' %}">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">保存并触发流程</button>
</form>

内容的提问来源于stack exchange,提问作者Prasanth Nelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:45:17