【问题标题】:Uncaught TypeError: $.ajax is not a function. Error even after not using the slim version未捕获的类型错误:$.ajax 不是函数。即使不使用超薄版本也会出错
【发布时间】:2020-08-07 04:30:35
【问题描述】:

我正在尝试制作动态下拉菜单,但在控制台中出现此错误。

Uncaught TypeError: $.ajax is not a function
at HTMLSelectElement.<anonymous> ((index):148)
at HTMLSelectElement.dispatch (jquery-3.4.1.min.js:2)
at HTMLSelectElement.v.handle (jquery-3.4.1.min.js:2)

我正在关注一个页面来制作这个下拉菜单,这是link

views.py

from django.shortcuts import render
from . import forms 

from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_protect
from django.forms import modelformset_factory
import requests
import urllib.parse
from apply_main.models import *

def apply(request):

    def getLonLat(subdistrict,district,state):
        address = str(subdistrict)+", "+str(district)+", "+str(state)
        url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) +'?format=json'

        response = requests.get(url).json()
        return response[0]["lat"],response[0]["lon"]

    form = forms.ApplyForm()
    if request.method == 'POST':
        form = forms.ApplyForm(request.POST)

        if form.is_valid():
            application = form.save(commit=False)

            
            application.save()

            return HttpResponseRedirect(reverse('apply_main:apply'))
    
    context = {
        'form':form,
    }
    return render(request, 'apply_main/apply_form.html', context)

def load_districts(request):
    state_id = request.GET.get('state')
    print(state_id,"\n"*5)
    districts = District.objects.filter(state_id=state_id).order_by('name')
    return render(request, 'apply_main/dist_dropdown_list_options.html', {'districts': districts})

def load_subdistricts(request):
    district_id = request.GET.get('district')
    subdistricts = Subdistrict.objects.filter(district_id=district_id).order_by('name')
    return render(request, 'apply_main/subdist_dropdown_list_options.html', {'subdistricts': subdistricts})

模型.py

from django.db import models
from django.contrib.auth.models import User

class State(models.Model):
    name = models.CharField(max_length=64)

    def __str__(self):
        return self.name
    
class District(models.Model):
    name = models.CharField(max_length=64)
    state = models.ForeignKey(State,on_delete=models.CASCADE)
    
    def __str__(self):
        return self.name

class Subdistrict(models.Model):
    name = models.CharField(max_length=64)
    district = models.ForeignKey(District,on_delete=models.CASCADE)
    
    def __str__(self):
        return self.name

class Apply(models.Model):
    first_name = models.CharField(max_length=64)
    middle_name = models.CharField(max_length=64,blank=True)
    last_name = models.CharField(max_length=64)
    aadhaar_number = models.IntegerField(unique=True,blank=False)
    published = models.DateTimeField(auto_now_add=True)
    phone_number = models.IntegerField(unique=True,blank=False)
    dob = models.DateField()
    lon = models.FloatField()
    lat = models.FloatField()
    subdistrict = models.ForeignKey(Subdistrict,on_delete=models.CASCADE)
    district = models.ForeignKey(District,on_delete=models.CASCADE)
    state = models.ForeignKey(State,on_delete=models.CASCADE)

    
    def __str__(self):
        return str(self.first_name)

forms.py

from django import forms
from apply_main.models import *

class ApplyForm(forms.ModelForm):
    dob = forms.DateField(widget=forms.DateInput(
        attrs={
            'placeholder': 'MM/DD/YYYY'
        }
    ))
    
    middle_name = forms.CharField(widget=forms.TextInput(
        attrs={
            'placeholder':'Optional'
        }
    ))

    class Meta:
        model = Apply
        fields = [
            'first_name',
            'middle_name',
            'last_name',
            'aadhaar_number',
            'phone_number',
            'dob',
            'state',
            'district',
            'subdistrict',            
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['district'].queryset = District.objects.none()
        self.fields['subdistrict'].queryset = Subdistrict.objects.none()

urls.py

from django.urls import path
from . import views
from donate import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

app_name = "apply_main"

urlpatterns = [
    path('apply/',views.apply,name='apply'),
    path('ajax/load-districts/', views.load_districts, name='ajax_load_districts'),
    path('ajax/load-subdistricts/', views.load_subdistricts, name='ajax_load_subdistricts'),

]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

apply_form.html

{% extends 'base.html' %}
{% load static %}

{% block head_block %}
<link rel="stylesheet" type="text/css" href="{% static 'index.css' %}">
{% endblock head_block %}

{% block body_block %}

  <h2>Person Form</h2>

  <form method="post" id="applyForm" data-districts-url="{% url 'apply_main:ajax_load_districts' %}" data-subdistricts-url="{% url 'apply_main:ajax_load_subdistricts' %}" novalidate>
    {% csrf_token %}
    <table>
      {{ form.as_table }}
    </table>
    <button type="submit">Save</button>
  </form>
  <script>console.log("outside");</script>
  
  
  <script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <script>
    $("#id_state").change(function () {
      var url = $("#applyForm").attr("data-districts-url");  // get the url of the `load_cities` view
      var stateId = $(this).val();  // get the selected country ID from the HTML input
      console.log("inside");
      console.log(url);
      console.log(stateId);
      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
          'state': stateId       // add the country id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_cities` view function
          $("#id_district").html(data);  // replace the contents of the city input with the data that came from the server
        }
      });

    });

    $("#id_district").change(function () {
      var url = $("#applyForm").attr("data-subdistricts-url");  // get the url of the `load_cities` view
      var districtId = $(this).val();  // get the selected country ID from the HTML input
      console.log("inside");
      console.log(url);
      console.log(districtId);
      $.ajax({                       // initialize an AJAX request
        url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
        data: {
          'district': districtId       // add the country id to the GET parameters
        },
        success: function (data) {   // `data` is the return of the `load_cities` view function
          $("#id_subdistrict").html(data);  // replace the contents of the city input with the data that came from the server
        }
      });

    });
  </script>

{% endblock %}

dist_dropdown_list_options.html

<option value="">---------</option>
{% for district in districts %}
<option value="{{ district.id }}">{{ district.district_name }}</option>
{% endfor %}

subdist_dropdown_list_options.html

<option value="">---------</option>
{% for subdistrict in subdistricts %}
<option value="{{ subdistrict.id }}">{{ subdistrict.subdistrict_name }}</option>
{% endfor %}

如果需要任何其他信息,请告诉我。

GitHub 链接 - https://github.com/deshiyan1010/electronics-donation

【问题讨论】:

  • 你是否在base.html 中添加了 jquery 也是因为版本不匹配时也会发生这种情况
  • 是的。 jQuery 3.5.1 苗条分钟。但是不会被上面的规范覆盖吗?
  • 尝试将此 min.js 放入基础 html 并从此处删除
  • 非常感谢普鲁思维。它正在工作!!!
  • 谢谢@PruthviBarot,库脚本放在哪里非常重要。而且有时不是很直观。但就我而言,您的建议立即奏效!

标签: javascript python jquery django ajax


【解决方案1】:

我可能在这里遗漏了一些东西,但是您绑定到 '#id_state' 的更改侦听器...这个元素在哪里?您是否省略了其他标记?此外,当您尝试跟踪 $ 对象时会发生什么? $.ajax 对象?

我已经在本地复制了您的代码,并且在 jQuery 库中定位 ajax 方法没有任何问题,尽管当它证明无法定位 id_state 元素时,它的本机捕获未能引发错误。

快速修改你的脚本,改变...

$("#id_state").change(function () {

...与其原版 JS 等效...

document.querySelector("#id_state").addEventListener('change', () =&gt; {

...明确该字段的遗漏。

但是,当我手动提供一个已获得必需 ID id_state 的字段时,它会逐步执行 ajax 请求(在代码的两个版本中),尽管我(不出所料)在尝试连接到我的本地网络上不可用的 URL。

您可以提供更多数据吗?

【讨论】:

  • ApplyForm 内的meta 类中,您似乎已将字段声明为'state''district''subdistrict',尽管在其他地方您引用了'state_name',和'state_id'。如果是我尝试调试它,我会快速扫描并验证我的变量、字段名称/ID,然后立即跟踪对象和绑定。
  • 请忽略那部分。我已将其注释掉以进行测试。我已删除该评论部分以避免混淆。
  • 我会给出 GitHub repo 链接。
  • 请检查 GitHub 存储库:github.com/deshiyan1010/electronics-donation
  • 非常感谢 NerdyDeeds。 Prithvi 给出了一个解决方案,它现在可以工作了。
猜你喜欢
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多