示例
页面输入两个整数,通过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)
检测内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <script src="/static/jquery-3.5.1.min.js"></script> </head> <body> <form method="post"> {#<p>用户名:<input type="text" name="user" id="i1"> <span id="error" style="color: red"></span> </p>#} 用户名: <input type="text" name="user" id="i1"/><span id="error" style="color:red"></span> <p>密码:<input type="password" name="pwd"> </p> <p><input type="submit" value="注册"></p> </form> <script > $("#i1").blur(function () { $.ajax({ url: "/check/", type: "post", data:{"user": $("#i1").val()}, success: function (data) { console.log(data); $("#error").html(data.msg); } }) }) </script> </body> </html>
path('register/', views.register), path('check/', views.check),
from django.shortcuts import HttpResponse, render from django.http import JsonResponse def register(request): user = request.POST.get("user") print(user) return render(request, 'register.html') def check(request): user = request.POST.get('user') print(user) if user == 'a': return JsonResponse({'status':1, 'msg':'用户名已存在'}) else: return JsonResponse({'status':0, 'msg':'可用的用户名'})