欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django1.7+JQuery+Ajax驗證用戶注冊集成小例子

 更新時間:2017年04月08日 22:23:23   投稿:mdxy-dxy  
下面是散仙使用Django+Jquery+Ajax的方式來模擬實現(xiàn)了一個驗證用戶注冊時,用戶名存在不存在的一個小應(yīng)用。注意,驗證存在不存在使用的是Ajax的方式,不用讓用戶點擊按鈕驗證是否存在,需要的朋友可以參考下

Ajax的出現(xiàn)讓W(xué)eb展現(xiàn)了更新的活力,基本所有的語言,都動態(tài)支持Ajax與起服務(wù)端進行通信,并在頁面實現(xiàn)無刷新動態(tài)交互。 下面是散仙使用Django+Jquery+Ajax的方式來模擬實現(xiàn)了一個驗證用戶注冊時,用戶名存在不存在的一個小應(yīng)用。注意,驗證存在不存在使用的是Ajax的方式,不用讓用戶點擊按鈕驗證是否存在。 截圖如下:

頁面HTML代碼如下:

<!DOCTYPE html>
<html>
<head lang="en">
 <meta charset="UTF-8">
<title>Ajax驗證測試</title>
</head>
<script src="/static/jquery/jquery211.js"></script>
<script> 
$(function(){ 
$("#pu").bind('keydown',function(){
c=$("#pu").val()
$.ajax({
type:"POST",
url:"/ccc/",
data:{name:c},
dataType:"json",
 success: function(data) {
$("#p").text(data.msg)
}
}); 
}) 
}) 
</script>
<body> 
輸入名字進行校驗:<input id="pu"type="text"> <span id="p"style="color: red"></span>
</body>
</html>

view端的代碼,注意csrf的裝飾方法,針對post請求:

from django.shortcuts import render
from django.http.response import HttpResponse
# Create your views here.
from django.shortcuts import render_to_response
#導(dǎo)入render_to_response
from django.shortcuts import render_to_response
#導(dǎo)入包裝的csrf請求,對跨站攻擊腳本做處理
from django.views.decorators.csrf import csrf_exempt
 
import json
 
def tt(request):
 return render_to_response('em/add.html')
 
 
names=list();
names.append("zhangsa")
names.append("aa")
names.append("b")
names.append("c")
 
 
@csrf_exempt
def ccc(request):
 
name=request.POST.get("name",None)
rtxt="";
 if name is not None:
 b=name in names
 if b:
#print("名字已經(jīng)存在!",name)
rtxt="名字已經(jīng)存在!"
else:
print("名字不存在!")
rtxt="名字不存在!"
 #print("獲取的名字是:NU",name)
 
 return HttpResponse(json.dumps({"msg":rtxt}))

urls里面的代碼:

#ajax校驗
url(r'^ccc/$',ccc),

注意里面用到了json.dumps函數(shù)來生成json對象,注意詞典的形式,在測試之前,最后,先訪問一下看看,json數(shù)據(jù)是否能拿到.

ajax驗證沒有問題之后,我們就可以在前端進行了,測試效果就是散仙開頭所截圖,本文的重點在于驗證ajax的功能調(diào)用,所以并沒有直接從數(shù)據(jù)庫里面獲取數(shù)據(jù)進行驗證,而是使用了list集合,進行了數(shù)據(jù)的模擬,如果想做的更完美一點,可以把數(shù)據(jù)庫部分實現(xiàn),這樣就與真實中的網(wǎng)站驗證場景就一樣了。

相關(guān)文章

最新評論