添加一个 register.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<p>用户名<input id="username" type="text" name="username" onblur="func1(this)" />
<span id="error"></span>
</p>
<p>密码<input type="text" name="pwd" /></p>
<input type="submit" value="submit">
</form>
<script>
function func1(self) {
var username=self.value;
var xmlhttp=createXMLHttpRequest();
xmlhttp.open("POST","/ajax_register/",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+username);
xmlhttp.onreadystatechange=function () {
if(xmlhttp.readyState===4 && xmlhttp.status===200){
var s=xmlhttp.responseText
if (s=="1"){
document.getElementById("error").innerHTML="用户名已经注册!"
}
}
}
}
function createXMLHttpRequest() {
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
// 适用于IE6
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try {
// 适用于IE5.5,以及IE更早版本
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e) {
}
}
}
return xmlHttp;
}
</script>
</body>
</html>
修改 views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def ajax_register(request):
if request.method=="POST":
username=request.POST.get("username")
if username=="klvchen":
return HttpResponse("1")
return HttpResponse("0")
return render(request,"register.html")
修改 urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('ajax_register/', views.ajax_register),