Django入门教程(三):前后端数据交互(POST,GET传参)

大家好我是连人。本期本来是打算直接写用户的登录和注册的,但是最后还是决定从最基本的写起。

后端向前端传递数据

我们还是从上一篇的hello world入手。
这个世界既又快乐,亦有悲伤
错的不是我,是这个世界。(不是)
我们自然希望这个世界是快乐的。
我们把world变成变量,这样可以及时反映我们对这个世界的期望。
于是,我们在后端定义world是快乐的

def home(request):
    world = "Happy World!"
    return render(request, 'Home.html', {"w": world})

world是定义的变量,w告诉前端这个变量的名字叫什么。这里为了区分我将后端的变量和前端的变量故意取了不同的名字。
前端的代码修改成:

<!DOCTYPE html>
<html>
    <head>
        <title>Hello world!</title>
    </head>
    <body>
        <p>Hello {{ w }}</p>
    </body>
</html>

变量名使用双大括号括起来。
在这里插入图片描述
很多时候,我们开发的网页不止需要一个变量,这个时候,我们可以使用locals()函数一口气把所有变量都传到前端。

def home(request):
    happy = "Happy"
    world = "World!"
    return render(request, 'Home.html', locals())

此时locals()传递的参数是后端的本来的名字
前端代码修改为

<!DOCTYPE html>
<html>
    <head>
        <title>Hello world!</title>
    </head>
    <body>
        <p>Hello {{ happy }} {{ world }}</p>
    </body>
</html>

但是locals()具有安全隐患,例如,你在登录界面判断用户的密码与输入是否一致,这个时候使用locals()传参,就有可能将用户的密码泄露。
所以我建议使用字典记录下你需要传递的参数,然后将字典传递给前端。

def home(request):
    happy = "Happy"
    world = "World!"
    context = {
        "happy": happy,
        "world": world
    }
    return render(request, 'Home.html', context)

前端向后端传递数据

GET和POST都是HTTP1.0的方法。

POST较GET更安全一些(但其实也没安全到哪儿去),但POST需建立两次连接而GET只需要一次,耗时长。

GET一般用于请求数据,POST一般用于提交数据,合理使用两种方法。

GET传参

在templates下新建g.html

<!DOCTYPE html>
<html>
    <head>
        <title>get</title>
    </head>
    <body>
        <p>{{ g }}</p>
    </body>
</html>

后端代码:

def g(request):
    if request.method == 'GET':
        g = request.GET.get('g')
        return render(request, 'g.html', locals())

urls.py中注册路由:

path('g/', views.g),

输入网址http://127.0.0.1:8000/g/?g=a
得到如下结果:
在这里插入图片描述
注意
1 get方法传递的数字是字符串而不是int型
2 多个参数之间用&连接
3 含有特殊符号(例如空格)会用%加数字代替(空格是%20)

POST表单传参

前端

<!DOCTYPE html>
<html>
    <head>
        <title>get</title>
    </head>
    <body>
        <form method="post" action="">
            {% csrf_token  %}   <!-- 防止跨站攻击 -->
            <input type="text" name="g"> <!-- 后端通过name拿到数据 -->
            <button type="submit">提交</button>
        </form>
        <br/>
        <p>{{ g }}</p>
    </body>
</html>

后端

def g(request):
    g = 'a'
    if request.method == 'POST':
        g = request.POST.get('g')
        return render(request, 'g.html', locals())
    return render(request, 'g.html', locals())

测试
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
很简单我也不详细解释了

转载注明出处

发布了10 篇原创文章 · 获赞 1 · 访问量 734

猜你喜欢

转载自blog.csdn.net/mirocky/article/details/103928436
今日推荐