一、views.pyjavascript
from django.http import JsonResponse
from captcha.models import CaptchaStore
def ajax_val(request):
if request.is_ajax():
cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])
if cs:
json_data = {'status':1}
else:
json_data = {"status":0}
return JsonResponse(json_data)
else:
json_data = {"status":0}
return JsonResponse(json_data)
二、urls.pyhtml
from users.views import ajax_val #引入剛纔添加在views.py中的代碼 urlpatterns = [ url(r'^ajax_val/', ajax_val, name='ajax_val'), #添加這一行 ]
三、 java
html文件中python
<script> $(function(){ $('.captcha').click(function(){ console.log('click'); $.getJSON("/captcha/refresh/", function(result){ $('.captcha').attr('src', result['image_url']); $('#id_captcha_0').val(result['key']) });}); $('#id_captcha_1').blur(function(){ // #id_captcha_1爲輸入框的id,當該輸入框失去焦點是觸發函數 json_data={ 'response':$('#id_captcha_1').val(), // 獲取輸入框和隱藏字段id_captcha_0的數值 'hashkey':$('#id_captcha_0').val() } $.getJSON('/ajax_val', json_data, function(data){ //ajax發送 $('#captcha_status').remove() if(data['status']){ //status返回1爲驗證碼正確, status返回0爲驗證碼錯誤, 在輸入框的後面寫入提示信息 $('#id_captcha_1').after('<span id="captcha_status" >*驗證碼正確</span>') }else{ $('#id_captcha_1').after('<span id="captcha_status" >*驗證碼錯誤</span>') } }); }); }) </script>