创建 add
应用
在 templates
内新建 add.html
文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>加法计算器</title>
</head>
<body>
<div>
<span>数字一</span>
<input type="number" id="num1" />
</div>
<div>
<span>数字二</span>
<input type="number" id="num2" />
</div>
<button id="button">计算结果</button>
<div id="result"></div>
<script>
const num1 = document.querySelector("#num1");
const num2 = document.querySelector("#num2");
document.querySelector("#button").addEventListener("click", () => {
fetch("/getadd/?num1=" + num1.value + "&num2=" + num2.value)
.then((data) => data.text())
.then((res) => {
document.querySelector("#result").innerHTML = "结果是:" + res;
});
});
</script>
</body>
</html>
修改 add
文件夹下的 views.py
文件
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'add.html')
def get_add(request):
result = int(request.GET.get('num1')) + int(request.GET.get('num2'))
return HttpResponse(result)
修改 urls.py
文件
from django.contrib import admin
from django.urls import path
from users import views
from add import views as add
urlpatterns = [
path('index/', views.index),
path('login/', views.login),
path('admin/', admin.site.urls),
path('add/', add.index),
path('getadd/', add.get_add),
]
访问 http://127.0.0.1:8000/add/
查看运行结果