1.urls.py
url(r'^jiafa', views.jiafa),
2.views.py
def jiafa(request): if request.method == "GET": return render(request, "jiafa.html", locals()) elif request.method == "POST": res = eval(json.dumps(request.POST)) obj = {} obj["status"] = "true" obj["v1"] = res["v1"] obj["v2"] = res["v2"] obj["v3"] = int(res["v2"])*int(res["v1"]) print(obj) return HttpResponse(json.dumps(obj))
3.jiafa.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/jiafa" method="POST" id="fm"> {% csrf_token %} <input type="text" name="v1"/>* <input type="text" name="v2"/>= <input type="text" name="v3" class="v3"/> {# <input id="btn" type="button" value="Ajax提交" onclick="ajaxsubmit();"/><span id="sp"></span>#} <input id="btn" type="button" value="Ajax提交"/><span id="sp"></span> </form> <script src="/static/plugins/jquery.min.js"></script> <script> $(function () { ajaxsubmit() }); function ajaxsubmit() { $("#btn").click(function () { $.ajax({ url: "/jiafa", data: $("#fm").serialize(), type: "POST", dataType: "json", success: function (args) { if (args.status) { var v = $(".v3").val(args.v3); console.log(v.val()); } }, error: function (arg) { console.log(arg) } }) }); } </script> </body> </html>
4.验证