创建了django项目之后,创建app。
配置urls:
from django.conf.urls import url
from django.contrib import admin
from myapp01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
]
配置views(app01.views):
from django.shortcuts import render
from django import forms
# Create your views here.
class InputForm(forms.Form):
# 下面使用的变量名必须和html中input标签的name值相同
username = forms.CharField(required=True)
password = forms.CharField(required=True)
def login(request):
if request.method == 'POST':
obj = InputForm(request.POST)
ret = obj.is_valid()
print(ret,obj.data)
if ret:
print(obj.clean())
else:
print(obj.errors)
return render(request, 'login.html')
配置tamplates(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<div>
<input type="text" name="username" />
</div>
<div>
<input type="password" name="password" />
</div>
<input type="button" value="提交" onclick="DoSubmit();"/>
</div>
<script src="/static/jquery-2.1.4.min.js"></script>
<script>
function DoSubmit() {
var input_dic = {};
$('input').each(function () {
var v = $(this).val();
var n = $(this).attr('name');
input_dic[n] = v;
});
console.log(input_dic);
$.ajax({
url:'/login/',
type:'POST',
data:input_dic,
success: function (rdata) {
console.log(rdata);
},
error: function () {
}
})
}
</script>
</body>
</html>
提交之后就可以获取输入的内容。