我在Django的AJAX怎么了?

时间:2019-03-20 19:55:35

标签: ajax django

我正在尝试在Django中实现AJAX。我有以下文件login.html 该文件包含表单和ajax脚本

{% extends 'services/base_visitor.html' %}
{% block title %}Log In{% endblock %}
{% block login_active %}active{% endblock %}

{% block body %}
<div class="container-fluid" style="position: absolute;top:20%;left:35%;width:30%;">



            <div class="panel panel-default">
                <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspLog In</h3>
                <center>
                <div class="panel-body">

                    {% if error_message %}
                        <p><strong>{{ error_message }}</strong></p>
                    {% endif %}
                    <!-- action="{% url 'login_user'%}" -->
                    <form class="form-horizontal" role="form"  action="{% url 'login_user'%}" method="POST" enctype="multipart/form-data">
                        {% csrf_token %}

                        <div class="form-group">
                            <!-- <label class="control-label col-sm-2" for="id_username">

                            </label> -->
                            <div class="col-sm-10">
                                <strong><span class="glyphicon glyphicon-user"></strong>&nbsp&nbsp&nbsp
                                    <input id="id_username" maxlength="30" name="id_username" type="text" placeholder="USERNAME"  style="font-family: Courier New;font-size: 15px;border: none; border-bottom: 2px solid black;">
                                    <div id="data"></div></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <!-- <label class="control-label col-sm-2" for="id_password">

                            </label> -->
                            <div class="col-sm-10">
                                <strong><span class="glyphicon glyphicon-asterisk"></strong>&nbsp&nbsp&nbsp
                                    <input id="id_password" maxlength="30" name="id_password" type="password"  placeholder="PASSWORD" style="font-family: Courier New;font-size: 15px; border: none; border-bottom: 2px solid black;"></span>
                            </div>
                        </div>
                        </center>
                        <div class="form-group">
                            &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="submit" class="btn btn-success">Submit</button>
                        </div>
                    </form>
                </div>

                <div class="panel-footer">
                    Don't have an account? <a href="http://localhost:8000/register/">Click here</a> to register.
                </div>

            </div>



</div>

{% endblock %}

{% block javascript %}
<script>
    $("#id_username").change(function(){
      alert("The text has been changed.");
    });

    $("#id_username").change(function () {
      var username = $("#id_username").val();
      console.log(username);
      $.ajax({
        type:"POST",
        url: '/ajax/validate_username/',
        data:{
            str:username,
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        dataType: 'json',
        success: function (data) {
            // alert("done")
            $("#data").html(data);
        }
      });

    });
</script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
{% endblock %}

以下是我的urls.py 寻找validate_username

from django.conf.urls import url
from . import views
from django.contrib import admin
from django.urls import path
from services import views as user_views
app_name = 'services'

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('base/', user_views.base, name='base'),
    path('login/', user_views.login_user, name='login_user'),
    path('index/', user_views.index, name='index'),
    path('login/', user_views.logout_user, name='logout_user'),
    # path(r'^signup/$', views.SignUpView.as_view(), name='signup'),
    url(r'^ajax/validate_username/$', user_views.validate_username, name='validate_username'),

]

以下是我的views.py 我检查用户是否已经存在,如果是,则返回成功,否则返回不成功。

from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout

from .forms import UserForm
from .models import UserProfile, Customer, Seller, User
from django.http import *

def validate_username(request):
    if request.method == 'POST':
        username = request.POST.get('str',None)
        # print(username)
        data = {
            'is_taken': user.objects.filter(username=username).exists()
        }

        if data.is_taken:
            return HttpResponse("Success!")
        else:
            return HttpResponse("NOT Success!")

无论何时用户在用户名字段中输入任何文本,我的ajax请求都将生效。但是,此预期的操作未完成。任何人,请澄清。 我还尝试使用jquery打印警报,但它似乎也不起作用。

1 个答案:

答案 0 :(得分:0)

我认为问题是绑定,请尝试以下操作:

window.onload = function() {
 // add your code change here
    $("#id_username").change(function(){
      alert("The text has been changed.");
    });

    $("#id_username").change(function () {
      var username = $("#id_username").val();
      console.log(username);
    });
}

$(document).ready= function() {
     // add your code change here
        $("#id_username").change(function(){
          alert("The text has been changed.");
        });

        $("#id_username").change(function () {
          var username = $("#id_username").val();
          console.log(username);
        });
    }