响应ajax请求的views方法需要加上@csrf_exempt注解,否则post请求报错,get可以设置favicon.ico,在url.py里加上path(‘favicon.ico’, RedirectView.as_view(url=r’media/favicon.ico’))即可
from django.contrib import adminfrom django.conf import settingsfrom django.conf.urls.static import staticfrom django.views.generic.base import RedirectViewfrom django.urls import pathimport app3.views as a3vurlpatterns = [path('admin/', admin.site.urls),path('a3/ajax', a3v.ajax),path('favicon.ico', RedirectView.as_view(url=r'media/favicon.ico')), # path('favicon.ico', RedirectView.as_view(url=r'static/img/1.jpg')), ]if settings.DEBUG:urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
//app3\views.pyfrom django.shortcuts import renderfrom django.http import HttpResponse,JsonResponsefrom django.shortcuts import redirect, renderfrom django.views.decorators.csrf import csrf_exempt@csrf_exemptdef ajax(request):if request.method == 'GET':print(request.GET)return JsonResponse({'code':555,'method':'doget'}) print(request.POST)return JsonResponse({'code':666,'method':'dopost'})
//app3\templates\test_extends.html{% extends 'base.html' %}{%load static%}{% block head %}<script src="/jquery-3.6.0.min.js"integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script><title>app3</title>{% endblock %}{% block body %}<p>This page has a body page</p><button type="button" id="getbutton">GET</button><button type="button" id="postbutton">POST</button><script>// $(function () {$("#getbutton").on("click", function (event) {$.ajax({type: "get",url: "/a3/ajax",data: {"id": 11 },dataType: "json"}).done(function (data) {console.log(data,typeof(data));}).fail(function (XMLHttpRequest, status, e) {console.error(XMLHttpRequest, status, e);});});$("#postbutton").on("click", function (event) {$.ajax({type: "post",url: "/a3/ajax",data: {"id": 111 },dataType: "json"}).done(function (data) {console.log(data,typeof(data));}).fail(function (XMLHttpRequest, status, e) {console.error(XMLHttpRequest, status, e);});});// });</script>{% endblock %}{% block foot %}<p>This page has a foot page</p>{% endblock %}