day02
回顾
1.核心对象 xhr
if(window.XMLHttpRequest){
reyurn new XMLHttpRequest();
}else{
return new ActiveXObject("Micosoft.XMLHTTP")
}
2.xhr 的成员
1.方法 -open(method,url,async)
2.属性 -readyState
4:服务器响应完毕
3.属性:-status
200:服务器正确响应所有的信息
4.属性 -responseText
5.事件 -onreadystatechange
6.方法 -send()
get :null
post:发送的数据
**************************************************************************************
1.使用AJAX发送POST请求
1.创建xhr
2.创建请求
1.请求方式改为post
2.有请求参数的话不能拼接在地址的后面
3.设置回调函数
4.设置请求消息头 - Content-Type
xhr.setRequestHeader(
"Content-Type",
"applocation/x-www-form-urlencoded"
)
5.发送请求
请求数据在send()的参数位置处
示例:
xhr.send("name=wanwc&age=20&gender=男");
2.json
1.介绍json
json:javascript object notation
js 对象 表现方式
以js对象的格式前后端交互的字符串数据
2.jso -js对象
使用 js 对象表示一个人的信息,包含如下属性:
姓名:sj
年龄:25
身高:152
体重:100
var obj = {
name:"sj",
age:25,
height:152,
weight:100
}
console.log("姓名:"+obj.name);
1 from django.conf.urls import url 2 from . import views 3 4 urlpatterns = [ 5 # 1. 演示创建xhr 6 url(r'^01-createxhr/$', views.create_views), 7 # 2. 演示使用ajax发送get请求的步骤 8 url(r'^02-server/$', views.server02_views), 9 url(r'^02-ajax-get/$', views.ajaxget_views), 10 # 3. 演示使用ajax发送get请求并附带参数 11 url(r'^03-ajax-get-params/$', views.getparams_views), 12 url(r'^03-server/$', views.server03_views), 13 # 4. 使用 AJAX 完成注册操作 14 url(r'^04-register/$',views.register_views), 15 url(r'^04-checkuname/$',views.checkuname_views), 16 url(r'^04-reguser/$',views.reguser_views), 17 url(r'^04-regpost/$',views.regpost_views), 18 # 5. 使用AJAX发送post请求 19 url(r'^05-ajax-post/$',views.post_views), 20 url(r'^05-server/$',views.server05_views), 21 # 6. 使用AJAX读取数据 22 url(r'^06-ajax-users/$',views.users_views), 23 url(r'^06-server/$',views.server06_views), 24 # 7. 在前端中处理JSON格式字符串 25 url(r'^07-json/$',views.json_views), 26 ] 27 28 29 30 31 32 33 34 35 36 37 38
1 from django.http import HttpResponse 2 from django.shortcuts import render 3 4 # Create your views here. 5 from ajax.models import Users 6 7 8 def create_views(request): 9 return render(request,'01-createxhr.html') 10 11 def server02_views(request): 12 return HttpResponse("这是server02的响应内容") 13 14 def ajaxget_views(request): 15 return render(request,'02-ajax-get.html') 16 17 def getparams_views(request): 18 return render(request,'03-ajax-get-params.html') 19 20 def server03_views(request): 21 #1. 接收前端传递过来的两个参数 22 name = request.GET['name'] 23 age = request.GET['age'] 24 #2. 响应数据给前端 25 s = "姓名:%s,年龄:%s" % (name,age) 26 return HttpResponse(s) 27 28 def register_views(request): 29 return render(request,'04-register.html') 30 31 def checkuname_views(request): 32 # 1.接收前端传递过来的参数 - uname 33 uname = request.GET['uname'] 34 # 2.判断uname在Users实体中是否存在[查询操作] 35 users = Users.objects.filter(uname=uname) 36 # 3.根据查询结果给出响应 37 if users: 38 return HttpResponse("1") 39 return HttpResponse("0") 40 41 def reguser_views(request): 42 # 1.接收前端传递的数据 43 uname = request.GET['uname'] 44 upwd = request.GET['upwd'] 45 uemail = request.GET['uemail'] 46 nickname = request.GET['nickname'] 47 # 2.通过实体类实现增加操作(通过异常处理处理增加失败的问题) 48 try: 49 Users.objects.create(uname=uname,upwd=upwd,uemail=uemail,nickname=nickname) 50 return HttpResponse("1") 51 except Exception as ex: 52 print(ex) 53 return HttpResponse("0") 54 55 def post_views(request): 56 return render(request,'05-post.html') 57 58 59 def server05_views(request): 60 uname = request.POST['uname'] 61 upwd = request.POST['upwd'] 62 msg = "用户名:%s,密码:%s" % (uname,upwd) 63 return HttpResponse(msg) 64 65 def regpost_views(request): 66 # 1.接收前端传递的数据 67 uname = request.POST['uname'] 68 upwd = request.POST['upwd'] 69 uemail = request.POST['uemail'] 70 nickname = request.POST['nickname'] 71 # 2.通过实体类实现增加操作(通过异常处理处理增加失败的问题) 72 try: 73 Users.objects.create(uname=uname, upwd=upwd, uemail=uemail, nickname=nickname) 74 return HttpResponse("1") 75 except Exception as ex: 76 print(ex) 77 return HttpResponse("0") 78 79 def users_views(request): 80 return render(request,'06-ajax-users.html') 81 82 def server06_views(request): 83 users = Users.objects.all() 84 msg = "" 85 for u in users: 86 msg += "%s_%s_%s_%s_%s|" % (u.id,u.uname,u.upwd,u.uemail,u.nickname) 87 msg = msg[0:-1] 88 return HttpResponse(msg) 89 90 91 def json_views(request): 92 return render(request,'07-json.html') 93 94 95 96
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="/static/common.js"></script> 7 <script src="/static/jquery-1.11.3.js"></script> 8 <script> 9 $(function(){ 10 /** 11 * 为 #btnPost 绑定 click 事件 12 */ 13 $("#btnPost").click(function(){ 14 //1.创建xhr 15 var xhr = createXhr(); 16 //2.创建请求 17 xhr.open("post","/ajax/05-server/",true); 18 //3.设置回调函数 19 xhr.onreadystatechange = function(){ 20 if(xhr.readyState==4 && xhr.status == 200){ 21 alert(xhr.responseText); 22 } 23 } 24 //4.设置请求消息头 25 xhr.setRequestHeader( 26 "Content-Type", 27 "application/x-www-form-urlencoded" 28 ); 29 //5.发送请求 30 var uname = $("#uname").val(); 31 var upwd = $("#upwd").val(); 32 // 获取csrfmiddlewaretoken的值 33 var csrf = $("[name='csrfmiddlewaretoken']").val(); 34 var params = "uname="+uname+"&upwd="+upwd+"&csrfmiddlewaretoken="+csrf; 35 xhr.send(params); 36 }); 37 }); 38 </script> 39 </head> 40 <body> 41 {% csrf_token %} 42 <p> 43 用户名称 <input type="text" id="uname"> 44 </p> 45 <p> 46 用户密码 <input type="password" id="upwd"> 47 </p> 48 <p> 49 <input type="button" id="btnPost" value="提交"> 50 </p> 51 52 53 54 55 56 57 58 59 60 61 62 63 </body> 64 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="/static/common.js"></script> 7 <script src="/static/jquery-1.11.3.js"></script> 8 <script> 9 $(function(){ 10 $("#btnShow").click(function(){ 11 var xhr = createXhr(); 12 xhr.open("get","/ajax/06-server",true); 13 14 xhr.onreadystatechange = function(){ 15 if(xhr.readyState==4 && xhr.status==200){ 16 var msg = xhr.responseText; 17 var html = ""; 18 var users = msg.split("|"); 19 for(var i=0;i<users.length;i++){ 20 html += "<tr>"; 21 //将每个人的信息通过 _ 再一次拆分 22 var infos = users[i].split('_'); 23 html += "<td>"+infos[0]+"</td>"; 24 html += "<td>"+infos[1]+"</td>"; 25 html += "<td>"+infos[2]+"</td>"; 26 html += "<td>"+infos[3]+"</td>"; 27 html += "<td>"+infos[4]+"</td>"; 28 html += "</tr>"; 29 } 30 $("#content").html(html); 31 } 32 } 33 34 xhr.send(null); 35 }); 36 }); 37 </script> 38 </head> 39 <body> 40 <button id="btnShow">显示</button> 41 <table width="500" border="1"> 42 <thead> 43 <tr> 44 <th>ID</th> 45 <th>用户名</th> 46 <th>密码</th> 47 <th>邮箱</th> 48 <th>昵称</th> 49 </tr> 50 </thead> 51 <tbody id="content"></tbody> 52 </table> 53 </body> 54 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="/static/jquery-1.11.3.js"></script> 7 <script> 8 $(function(){ 9 $("#btnJSON").click(function(){ 10 //1.模拟一个JSON字符串 11 var flight = '{"flightNO":"NH980","from":"PEK","to":"KIX","time":"14:20"}'; 12 //2.通过JSON.parse()将JSON串转换成JS对象 13 var obj = JSON.parse(flight); 14 //console.log(obj); 15 //3.解析对象 16 console.log("航班号:"+obj.flightNO); 17 console.log("出发:"+obj.from); 18 console.log("到达:"+obj.to); 19 console.log("时间:"+obj.time); 20 }); 21 22 23 $("#btnJSONArr").click(function(){ 24 var str = '[{"flightNO":"NH980","from":"PEK","to":"KIX","time":"14:20"},{"flightNO":"NH979","from":"KIX","to":"PEK","time":"09:20"}]'; 25 26 var arr = JSON.parse(str); 27 28 $(arr).each(function(i,obj){ 29 console.log("下标为"+i+"的元素"); 30 console.log("航班号:"+obj.flightNO); 31 console.log("出发:"+obj.from); 32 console.log("到达:"+obj.to); 33 console.log("时间:"+obj.time); 34 }); 35 36 /*for(var i=0;i<arr.length;i++){ 37 var obj = arr[i]; 38 }*/ 39 }); 40 }); 41 </script> 42 </head> 43 <body> 44 <button id="btnJSON">JSON串->JS对象</button> 45 <button id="btnJSONArr">JSON串->JS数组</button> 46 </body> 47 </html>