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

如何用JS和AJAX点击按钮将页面API数据存入Django数据库

实现无刷新提交国家和日期到Django数据库的步骤详解

1. 后端Django配置

1.1 确认Model(models.py)

先确保你的CountryData模型定义正确:

# models.py
from django.db import models

class CountryData(models.Model):
    country = models.CharField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return f"{self.country} - {self.date}"

执行数据库迁移使模型生效:

python manage.py makemigrations
python manage.py migrate

1.2 编写AJAX处理视图(views.py)

新增视图函数接收POST请求,解析参数并保存数据,返回JSON响应:

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import CountryData
import json

# 生产环境建议移除csrf_exempt,改用前端携带CSRF令牌
@csrf_exempt
def save_country_data(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            country = data.get('country')
            date = data.get('date')
            
            if country and date:
                # 若需避免重复数据,改用get_or_create
                # CountryData.objects.get_or_create(country=country, date=date)
                CountryData.objects.create(country=country, date=date)
                return JsonResponse({'status': 'success', 'message': '数据保存成功'})
            else:
                return JsonResponse({'status': 'error', 'message': '缺少国家或日期参数'}, status=400)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    else:
        return JsonResponse({'status': 'error', 'message': '仅支持POST请求'}, status=405)

1.3 配置URL路由(urls.py)

将新增视图映射到URL:

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    # 你的其他URL规则...
    path('save-country-data/', views.save_country_data, name='save_country_data'),
]

2. 前端页面实现(allcountries.html)

2.1 渲染卡片时绑定数据

在每个新冠数据卡片中,把国家和日期通过data-*属性绑定到按钮上:

<!-- 卡片示例 -->
<div class="country-card">
    <h3>{{ country.name }}</h3>
    <p>数据日期:{{ record.date }}</p>
    <button 
        class="add-record-btn" 
        data-country="{{ country.name }}" 
        data-date="{{ record.date|date:'Y-m-d' }}"
    >ADD TO MY RECORDS</button>
</div>

日期统一用Y-m-d格式,确保后端能正确解析为Date类型。

2.2 编写AJAX提交脚本

在页面底部添加JS代码,监听按钮点击事件并发送无刷新请求:

// 获取所有添加按钮
const addButtons = document.querySelectorAll('.add-record-btn');

addButtons.forEach(button => {
    button.addEventListener('click', function() {
        // 从按钮属性中提取数据
        const country = this.dataset.country;
        const date = this.dataset.date;

        // 发送AJAX请求
        fetch('/save-country-data/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                // 携带CSRF令牌,生产环境必须
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ country, date })
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                // 提交成功后的交互:修改按钮状态
                this.textContent = '已添加';
                this.disabled = true;
                alert(data.message);
            } else {
                alert('保存失败:' + data.message);
            }
        })
        .catch(err => {
            console.error('请求错误:', err);
            alert('请求失败,请稍后重试');
        });
    });
});

// 辅助函数:获取Django设置的CSRF令牌Cookie
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.startsWith(name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

3. 生产环境优化提示

  • CSRF防护:移除视图上的csrf_exempt装饰器,前端通过上述getCookie函数携带令牌,避免跨站请求伪造。
  • 数据校验:后端可添加日期格式校验,比如用datetime.datetime.strptime验证日期格式是否合法。
  • 重复数据拦截:使用get_or_create替代create,防止同一国家同一日期的重复数据存入数据库。

内容的提问来源于stack exchange,提问作者Batool Ragayah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:20:34