- 响应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 admin
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import RedirectView
from django.urls import path
import app3.views as a3v
urlpatterns = [
path('admin/', admin.site.urls),
path('a3/ajax', a3v.ajax),
path('favicon.ico', RedirectView.as_view(url=r'media/favicon.ico')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
//app3\views.py
from django.short
cuts import render
from django.http import HttpResponse,JsonResponse
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def 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="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">script>
<title>app3title>
{% endblock %}
{% block body %}
<p>This page has a body pagep>
<button type="button" id="getbutton">GETbutton>
<button type="button" id="postbutton">POSTbutton>
<script>
$("#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 pagep>
{% endblock %}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51