1.3笔记

 在web开发中,表单提交是一个很常见的功能,在django中,使用form表单提交较为简单,需要注意在表单中添加{% csrf_token %},如果不想这样做,也可以在对应的view方法中添加装饰器@csrf_exempt,强制不使用csrf认证。

    如果是ajax提交表单,则相对复杂一些,在ajax提交时,除了提交你的表单内容数据,还要添加一个请求头数据, headers:{"X-CSRFToken":$.cookie("csrftoken")},$.cookie("csrftoken")使用了jquery的cookie框架,可以方便的获取cookie数据。如果不加上这个请求头,那么请求将会失败,且是400系列的请求异常。

    那么废话不多说,直接上代码吧(分别演示form表单和ajax提交的情况):

    urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index),
    path('add_blog',views.add_blog,name='add_blog')
]

    views.py:

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, render_to_response


# Create your views here.
def index(request):
    return render(request,'index.html')

def add_blog(request):
    if request.is_ajax():
        title = request.POST.get('title')
        content = request.POST.get('content')
        data = {}
        data['status'] = '0'
        data['message'] = '传递数据成功'
        data['data'] = {'title':title,'content':content}
        return JsonResponse(data)
    else:
        title = request.POST.get('title')
        content = request.POST.get('content')
        print(title)
        print(content)
        return render(request, 'index.html', locals())

index.html:

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>以form方式添加博客</h1>
    <form action="{% url 'add_blog' %}" method="post">
        {% csrf_token %}
        <label>博客标题</label>
        <input type="text" name="title">
        <label>博客内容</label>
        <input type="text" name="content">
        <button  type="submit">添加</button>
    </form>
    <h4>提交的数据:title:{{ title }},content:{{ content }}</h4>

    <h1>以ajax方式添加博客</h1>
    <label>博客标题</label>
    <input type="text" id="title">
    <label>博客内容</label>
    <input type="text" id="content">
    <button type="button" id="commit_btn">添加</button>
    <div id="ajax_ret"></div>
</body>

<script src="{% static 'jquery-1.12.4.min.js' %}"></script>
<script src="{% static 'jquery.cookie.js' %}"></script>

<script>
    $("#commit_btn").click(function () {
        $.ajax({
                url:'{% url 'add_blog' %}',
                method:'post',
                data:{title:$("#title").val(),content:$('#content').val()},
                headers:{"X-CSRFToken":$.cookie("csrftoken")},
                success:function (data) {
                    $('#title').val('')
                    $('#content').val('')
                    $('#ajax_ret').html("<H4>后台返回的数据:状态码:"+data.status+",说明信息:"+data.message+",返回数据:"+data.data.title+","+data.data.content+"</H4>")
                },
                error:function (data) {
                    alert(data.status)
                }
            }
        )
    })

</script>

</html>

好了,来看张页面截图吧:

猜你喜欢

转载自blog.csdn.net/qq495966654/article/details/85857554
1.3