<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="{%static 'js/jquery-1.11.3.js'%}"></script>
<script src="{%static 'js/login_.js'%}"></script>
<body>
<form action="" method="post">
<input type="text" placeholder="请输入用户名" name="uname">
<sapn id="show-name"></span>
</body>
</html>
# 此部分为加载的login.js
$(function(){
$("[name='uname']").click(function(){
var username = $(this).val();
if(username==""){
$("show-name").html("用户名不能为空");
return;
}$.ajax({
url:"/index/test/",
data:{"username":username, "type":"自定义名称,以便处理对应的ajax"},
type:"type",
dataType:"json",
async:"true",
success:function(data,status,xhr){
console.log("成功获取服务器响应");
msg = data.msg;
if(msg=="ok"){
$("show-name").html("用户名可以使用");
} else{
$("show-name").html("用户名已存在"); }
},
error:function(xhr,status,error){
console.log(error);
console.log(status);
}
})
})
})
# 需要在django中对应函数上加上
# 必须导入下面的csrf_exempt ,不然会出现403错误
from django.views.decorators.csrf import csrf_exempt
import json
# 这是视图处理的函数
@csrf_exempt
def test_views(request):
type = request.POST.get('type')
if type == 'hasuser':# 这是ajax中自定义的type类型,以便自己好对应处理
username = request.POST.get('username', None)
print("username------->", username)
if username:
count = User.objects.filter(uname=username).count()
if count > 0:
result = dict(msg='no_ok')
else:
result = dict(msg='ok')
# 必须要返回一个json字符串给ajax
return HttpResponse(json.dumps(result))