为什么我在Django应用中的jquery无法正常工作?

时间:2018-11-05 00:41:26

标签: javascript jquery ajax django

我正在使用JQuery和Django实现一个依赖下拉列表。但是,我仍然不知道为什么这个jquery无法正常工作。

我的模板:

{% block style %}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/style.css' %}"/>
{% endblock %}

{% block script %}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type='text/javascript' src="{% static 'js/ajax_load_rooms.js' %}"></script>
{% endblock %}

{% block content %}
    <div class="container-">
        <div class="wrapper">
            <form id='selectForm' method="post" data-rooms-url="{% url 'ajax_load_rooms' %}">
                {% csrf_token %}
                        <div class="building">
                  <label for="building">Nhà học</label>
                  {{ form.building }}
                </div>
                <div class="room">
                             <label for="room">Phòng học</label>
                               {{ form.room }}
                </div>
                <button class="show-list btn btn-primary" >Thoi gian bieu</button>
            </form>
        </div>
    </div>
{% endblock %}

dropdown_room_list.html

<option value="">-------</option>
{% for room in rooms %}
<option value="{{ room.pk }}">{{ room.room }}</option>
{% endfor %}

我的jquery:

$("#id_building").change(function () {
  var url = $("#selectForm").attr("data-rooms-url");
  var buildingId = $(this).val();

  $.ajax({
    url: url,
    data: {
      'building': buildingId,
    },
    success: function (data) {
      $("#id_room").html(data);
    }
  });

});

我的观点:

def load_rooms(request):
    building = request.GET.get('building')
    room_list = Room.objects.filter(building__bid=building, availability=True)
    return render(request, 'dropdown-room-list.html', {'rooms': room_list})

我的网址:

from django.urls import path
from django.contrib.auth import views as auth_views

from .forms import LoginForm
from .views import *

urlpatterns = [
    path('accounts/login/', auth_views.LoginView.as_view(authentication_form=LoginForm, redirect_authenticated_user=True), name='login'),
    path('accounts/logout/', auth_views.logout_then_login, name='logout'),
    path('booking/list/', BookingListView.as_view(), name='booking_list'),
    path('booking/add/', BookingCreateView.as_view(), name='booking_add'),
    path('booking/<int:pk>/delete', BookingDeleteView.as_view(), name='booking_delete'),
    path('timetable/select/', TimetableSelectView.as_view(), name='select'),
    path('timetable/<str:building>/<str:room>/<int:year>/<int:week>', TimetableRoomView.as_view(), name='room_timetable'),
    path('ajax/load_rooms', load_rooms, name='ajax_load_rooms')
]

渲染的HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Tim phong</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="/static/css/style.css"/>


<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type='text/javascript' src="/static/js/ajax_load_rooms.js"></script>

</head>
<body>
    <header>
        <nav class="nav-bar">
            <ul class="left list">
                <li><a href="/booking/list/">Quản lý</a></li>
                <li><a href="/timetable/select/">Đặt phòng</a></li>

            </ul>
            <ul class="right list">
                <li><a href="/accounts/logout/">Đăng xuất</a></li>
            </ul>
        </nav>
    </header>

    <div class="container-">
        <div class="wrapper">
            <form id='selectForm' method="post" data-rooms-url="/ajax/load_rooms">
                <input type='hidden' name='csrfmiddlewaretoken' value='qvLwYOC9fKVkADkklqhL29UWNduOqJjwAlFYdLd6t03qWZ9z30z0BCsSElGoRsla' />
                        <div class="building">
                  <label for="building">Nhà học</label>
                  <select name="building" class="form-control form-control-sm" required id="id_building">
  <option value="" selected>---------</option>

  <option value="B1">Lecture Hall B1</option>

</select>
                </div>
                <div class="room">
                             <label for="room">Phòng học</label>
                               <select name="room" class="form-control form-control-sm" required id="id_room">
  <option value="" selected>---------</option>

  <option value="3">B1/101</option>

</select>
                </div>
                <button class="show-list btn btn-primary" >Thời gian biểu</button>
            </form>
        </div>
    </div>

</body>

请注意,我的javascript静态路径正确,模板呈现得很好,并且我可以看到正确代码的javascript路径。但是从属下拉功能似乎无法正常工作。

1 个答案:

答案 0 :(得分:0)

好的,我发现您的代码中缺少两件事-

  1. 无法在模板中找到id_building ID。
  2. 缺少ajax请求type (method),即发送数据时的post

仅对于building选择更改,您要更新其room。在这种情况下,您只能在ajax选择项上使用building查询-

  $("#id_building").change(function () {       
      $.ajax({
        url: "/ajax/load_rooms",
        method: "GET",
        async' false,
        data: {
          building : $(this).val(),
        },
        success: function (data) {
          //check your data
          console.log(data);
          // if data in id->room name format, it will work
          // if not change as per result data
          $.each(data, function(key, value) {
                htmlOption += '<option value="' + itemsMarque[key].id + '">'+ itemsMarque[key].name + '</option>';
            });

           $("#id_room").html(data);
         }
      });