添加一個 register.html 頁面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.pyajax
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.pydjango
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),