我所使用的是python3.6.5,django版本是2.0.5
GET请求:
(1) view.py
from django.http.response import HttpResponse
from django.shortcuts import render_to_response
import json
def Login(request):
if request.method == 'GET':
#创建参数字典
result = {}
username = request.GET.get('username')
telnum = request.GET.get('telnum')
date = request.GET.get('date')
result['username'] = username
result['telnum'] = telnum
result['date'] = date
#把字典转换成json
result = json.dumps(result)
return HttpResponse(result,content_type='application/json;charset=utf-8')
else:
#返回login页面
return render_to_response('login.html')
(2)urls.py
from django.contrib import admin
from django.urls import path
from web.views import Login
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',Login),#映射路径
]
(3)login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login/" method="post">
<h1>用户名:<input name="username"></h1>
<h1>密码:<input name="password"></h1>
<input type="submit" value="提交">
</form>
</body>
</html>
(4)输入http://localhost:8000/login/?username=oasd&telnum=123132&date=20180516页面返回参数字典
{"username": "oasd", "telnum": "123132", "date": "20180516"}
POST请求只需把view.py中的GET替换成POST,但要注意参数的个数
GET请求:
(1) view.py
from django.http.response import HttpResponse
from django.shortcuts import render_to_response
import json
def Login(request):
if request.method == 'GET':
#创建参数字典
result = {}
username = request.GET.get('username')
telnum = request.GET.get('telnum')
date = request.GET.get('date')
result['username'] = username
result['telnum'] = telnum
result['date'] = date
#把字典转换成json
result = json.dumps(result)
return HttpResponse(result,content_type='application/json;charset=utf-8')
else:
#返回login页面
return render_to_response('login.html')
(2)urls.py
from django.contrib import admin
from django.urls import path
from web.views import Login
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',Login),#映射路径
]
(3)login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login/" method="post">
<h1>用户名:<input name="username"></h1>
<h1>密码:<input name="password"></h1>
<input type="submit" value="提交">
</form>
</body>
</html>
(4)输入http://localhost:8000/login/?username=oasd&telnum=123132&date=20180516页面返回参数字典
{"username": "oasd", "telnum": "123132", "date": "20180516"}
POST请求只需把view.py中的GET替换成POST,但要注意参数的个数