欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django ajax 检测用户名是否已被注册

程序员文章站 2022-06-28 23:37:13
添加一个 register.html 页面 修改 views.py 修改 urls.py ......

添加一个 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),

Django ajax 检测用户名是否已被注册