环境:python3.7
IDE:pycharm
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> </head> <body> <button class="s1">send</button> <p class="name"></p> <hr> <input type="text" id="n1">+<input type="text" id="n2">=<input type="text" id="n3"><button class="cal">click</button> <script> //ajax的无参数请求 $(".s1").click(function () { //触发ajax事件 $.ajax({ url:"/ajax_handle/", type:"get", success:function (data) { console.log(data); $(".name").html(data); } }) }); //ajax发送参数,实现简单的加法 $(".cal").click(function () { $.ajax({ url:"/cal/", data:{"num1":$("#n1").val(),"num2":$("#n2").val(),}, success:function (data) { console.log(data); $("#n3").val(data) } }) }) </script> </body> </html>
urls.py
from django.contrib import admin from django.urls import path from app001 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index), path('ajax_handle/',views.ajax_handle), path('cal/',views.cal), ]
views.py
from django.shortcuts import render,redirect,HttpResponse # Create your views here. def index(request): return render(request,"index.html") def ajax_handle(request): return HttpResponse("第一个ajax代码。") def cal(request): num1=request.GET.get("num1") num2=request.GET.get("num2") ret=int(num1)+int(num2) return HttpResponse(str(ret))
运行Django项目,浏览器地址栏输入:http://127.0.0.1:8000/index.html,运行结果: