ajax的格式、简单使用编写,
url
from django.conf.urls import url from django.contrib import admin from app.views import classes from app.views import student from app.views import ajax urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^classes.html$',classes.get_classes),#不加^访问点击页面没反应 url(r'^add_classes.html$',classes.add_classes), url(r'^del_classes.html$', classes.del_classes), url(r'^edit_classes.html$',classes.edit_classes), url(r'^set_teacher.html$', classes.set_teacher), url(r'^student$', student.get_student), url(r'^add_student$', student.add_student), url(r'^del_student$', student.del_student), url(r'^edit_student$',student.edit_student), url(r'^ajax1$', ajax.ajax1), url(r'^ajax2$', ajax.ajax2), url(r'^ajax3$', ajax.ajax3), ]
ajax.py
from django.shortcuts import render,HttpResponse def ajax1(req): return render(req,'ajax1.html') def ajax2(req): user=req.GET.get('username') pwd=req.GET.get('password') import time time.sleep(5) return HttpResponse('你好') def ajax3(req): v1=req.POST.get('a1') v2=req.POST.get('a2') try: v3=int(v1)+int(v2) except Exception as e: v3='格式错误' return HttpResponse(v3)
ajax1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .btn{ display: inline-block; padding: 5px 15px; background: darkgoldenrod; color: white; cursor: pointer; } </style> </head> <body> <div><input placeholder="用户名" type="text"id="username"> <input placeholder="密码" type="password"id="password"> <div class="btn"onclick="sub()">提交</div> </div> <div><input type="text"id="q1">+ <input type="text"id="q2"> <div class="btn"onclick="addF()">等于</div> <input type="text"id="q3"> </div> <script src="/static/jquery-3.1.1.js"></script> <script> function sub() { var u=$('#username').val(); var p=$('#password').val(); {#console.log(u,p)#} $.ajax({ url:'ajax2',{# url里的那个路径,不是页面 #} type:'GET', data:{username:u,password:p}, success:function (arg) { console.log(arg){# 页面内部打印参数 #} } }) } function addF() { var v1=$('#q1').val() var v2=$('#q2').val() $.ajax({ url: 'ajax3', type:'POST', data: {'a1':v1,'a2':v2}, success:function (arg) { console.log(arg) $('#q3').val(arg) {# windows.location.reload()刷新页面,不是f5 #} } }) } </script> </body> </html>