from django.shortcuts import render,HttpResponse from django.http import JsonResponse import json # Create your views here. def index(request): if request.is_ajax(): n1=request.POST.get("n1") n2=request.POST.get("n2") # print(n1,n2) # print(type(n1)) sum=int(n2)+int(n1) re={"sum":sum,} # return HttpResponse(json.dumps(re)) return JsonResponse(re) return render(request,"index.html")
views.py
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <input type="text" id="n1" name="num1"> <input type="text" id=‘n2‘ name="num2"> <input type="text" id=‘n3‘ name="sum"> <input type="button" id="b" name="sum" value="点我"> <script> $(‘#b‘).click( function () { var n1 = $("#n1").val(); var n2 = $("#n2").val(); $.ajax({ url:"/index/", type:"post", data:{"n1":n1,"n2":n2,}, {#dataType:"json",#} success:function (ret) { //使用HttpResponse需要SON.parse {#var aa=JSON.parse(ret); #} //使用JsonResponse不需要 $("#n3").val(ret.sum); } }) } ) </script> </body> </html>
htm
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^index/‘, views.index), ]
urls.py
原文地址:https://www.cnblogs.com/Hale-wang/p/11695699.html
时间: 2024-11-09 00:41:05