Skip to content

Commit ec6c6d6

Browse files
committed
Add AJAX view and control to example app.
1 parent 13d2841 commit ec6c6d6

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

example/templates/index.html

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,21 @@ <h1>Index of Tests</h1>
1515
</ul>
1616
<p><a href="/admin/">Django Admin</a></p>
1717
{% endcache %}
18+
<p>
19+
<span>Value </span>
20+
<span id="session-value">{{ request.session.value|default:0 }}</span>
21+
<button id="increment" data-url="{% url 'ajax_increment' %}" type="button">Increment</button>
22+
</p>
23+
<script>
24+
const increment = document.querySelector("#increment");
25+
const value = document.querySelector("#session-value");
26+
increment.addEventListener("click", function () {
27+
fetch(increment.dataset.url).then( function (response) {
28+
response.json().then(function(data) {
29+
value.innerHTML = data.value;
30+
});
31+
});
32+
});
33+
</script>
1834
</body>
1935
</html>

example/urls.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
from django.urls import include, path
33
from django.views.generic import TemplateView
44

5+
from example.views import increment
6+
57
urlpatterns = [
68
path("", TemplateView.as_view(template_name="index.html")),
79
path("jquery/", TemplateView.as_view(template_name="jquery/index.html")),
810
path("mootools/", TemplateView.as_view(template_name="mootools/index.html")),
911
path("prototype/", TemplateView.as_view(template_name="prototype/index.html")),
1012
path("admin/", admin.site.urls),
13+
path("ajax/increment", increment, name="ajax_increment"),
1114
path("__debug__/", include("debug_toolbar.urls")),
1215
]

example/views.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from django.http import JsonResponse
2+
3+
4+
def increment(request):
5+
try:
6+
value = int(request.session.get("value", 0)) + 1
7+
except ValueError:
8+
value = 1
9+
request.session["value"] = value
10+
return JsonResponse({"value": value})

0 commit comments

Comments
 (0)