示例
页面输入两个整数,通过AJAX传输到后端计算结果并返回
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax_calc</title> <script src="/static/jquery-3.5.1.min.js"></script> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"> </head> <body> <input type="text" id="i1"> + <input type="text" id="i2"> = <input type="text" id="i3"> <input type="button" value="ajax提交" id="b1"> <script> $("#b1").on("click", function () { $.ajax({ url:"/ajax_add/", type:"GET", data:{"i1":$("#i1").val(),"i2":$("#i2").val()}, success:function (data) { $("#i3").val(data); } }) }) </script> </body> </html>
urlpatterns = [
path(‘admin/‘, admin.site.urls),
path(‘index/‘, views.index),
path(‘ajax_add/‘, views.ajax_add),
path(‘ajax_calc/‘, views.ajax_calc),
]
def ajax_calc(request):
return render(request, "ajax_calc.html")
def ajax_add(request):
i1 = int(request.GET.get("i1"))
i2 = int(request.GET.get("i2"))
ret = i1 + i2
return JsonResponse(ret, safe=False)