Ajax,偷偷摸摸的向后端发请求,后端收到请求后当前页面不会北刷新,常见的有再创建新用户的时候填写好所有的基本信息后提交后提示用户名已经被占用,但是此时我们填写的资料却还是在的,这就是使用了Ajax,否则的话页面会被刷新一次填写的资料也就没了
1.普通常用Ajax
首先它要基于jquery,因此在使用前需要导入jquery啦。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div><p>用户名:<input type="text" id="username" /></p></div> 9 <div><p>密码:<input type="password" id="pwd" /></p></div> 10 <input type="button" value="提交" onclick="SubmitForm();"/> 11 12 <script src="/static/jquery-1.12.4.js"></script> 13 14 <script> 15 function SubmitForm() { 16 $.ajax({ 17 18 url: '/web/ajax/', // 将请求发送到的url 19 type: 'POST', // 发送的方式 20 data: {'user': $('#username').val(), 'pwd': $('#pwd').val()}, // 发送的元数据内容,会做成一个字典 21 dataType: 'json', // 将上面的字典转成json格式发送,因为是向url发送,因此需要转换 22 success: function (data) { // 后台处理后返回的数据处理函数,data是后台传过来的数据 23 if (data.status){ 24 location.href = 'http://www.baidu.com'; 25 }else { 26 alert(data.message); 27 } 28 } 29 }) 30 } 31 </script> 32 </body> 33 </html>
1 def ajax(request): 2 if request.method == 'POST': 3 ret = {'status': False, 'message': ''} 4 user = request.POST.get('user', None) 5 pwd = request.POST.get('pwd', None) 6 if user == '111' and pwd == '222': 7 ret['status'] = True 8 return HttpResponse(json.dumps(ret)) 9 else: 10 ret['message'] = '用户名或密码错误' 11 return HttpResponse(json.dumps(ret)) 12 return render(request, 'ajax.html')
2.原生Ajax
它是直接使用XmlHttpRequest对象构造出来的
1 XmlHttpRequest对象的主要属性: 2 readyState:状态值(整数) 3 0 - 未初始化,尚未调用open() 4 方法; 5 1 - 启动,调用了open()方法,未调用send()方法; 6 2 - 发送,已经调用了send()方法,未接收到响应; 7 3 - 接收,已经接收到部分响应数据; 8 4 - 完成,已经接收到全部响应数据; 9 10 onreadystatechange:当readyState的值改变时自动触发执行其对应的函数(回调函数) 11 12 responseText:服务器返回的数据(字符串类型) 13 14 responseXML:服务器返回的数据(Xml对象) 15 16 states:状态码(整数) 17 18 statesText:状态文本(字符串)
1 function XhrAjax() { 2 // 回调函数 3 var xhr = new XMLHttpRequest(); 4 xhr.onreadystatechange = function () { 5 if (xhr.readyState == 4) { 6 // 当接收后台返回数据全部完毕后触发此函数:打印后台返回的文本字符串 7 console.log(xhr.responseText); 8 } 9 }; 10 xhr.open('GET', '/xhr_ajax/?a=1'); 11 // 设置请求方式及目标url,get请求参数直接写在url里 12 xhr.send(); 13 // get请求直接发送 14 } 15 function XhrAjaxPost() { 16 // 回调函数 17 var xhr = new XMLHttpRequest(); 18 xhr.onreadystatechange = function () { 19 if (xhr.readyState == 4) { 20 // 当接收后台返回数据全部完毕后触发此函数:打印后台返回的文本字符串 21 console.log(xhr.responseText); 22 } 23 }; 24 xhr.open('POST', '/xhr_ajax/'); 25 // 设置请求方式及目标url 26 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); 27 // post请求需要添加请求头信息 28 xhr.send('k1=v1;k2=v2'); 29 // post请求参数在send里填写 30 } 31 32 function XhrAjaxForm() { 33 var xhr = new XMLHttpRequest(); 34 xhr.onreadystatechange = function () { 35 if (xhr.readyState == 4) { 36 console.log(xhr.responseText); 37 } 38 }; 39 xhr.open('POST', '/xhr_ajax/'); 40 var form = new FormData(); 41 // 创建一个新的FormData对象往里加数据即可,机智的小django 42 form.append('user', 'bfmq'); 43 xhr.send(form); 44 }
3.跨域Ajax
在默认情况下浏览器会有同源策略,注意这里是浏览器的限制哦,浏览器不会接受从另外一个源加载过来的文档属性脚本等等
限制:XmlHttpRequest
不限制:具有src属性的标签们
jsonp实现:
1 function Ajax3(){ 2 // 创建一个script标签等待后台返回一个函数的字符串然后执行最后再删除这个script标签 3 var tag = document.createElement('script'); 4 tag.src = 'http://bfmq.com:8001/api/'; 5 document.head.appendChild(tag); 6 document.head.removeChild(tag); 7 } 8 function list(arg){ 9 // 后台返回的函数名的字符串 10 console.log(arg); 11 } 12 13 function Jsonp2() { 14 // jquery版本的就是对上述流程进行了一个封装 15 $.ajax({ 16 url: "http://bfmq.com:8001/api/", 17 type: 'GET', // POST也会被无视成GET 18 dataType: 'JSONP', 19 jsonp: 'callback', // 后台可以直接从callback=list获取传递的函数名作为变量传回来 20 jsonpCallback: 'list' 21 }) 22 } 23 24 function list(arg){ 25 console.log(arg); 26 }
1 def api(request): 2 func = request.GET.get('callback') 3 li = ['bfmq', 'dfmq', 'xfmq', 'nfmq'] 4 temp = "%s(%s)" % (func, json.dumps(li)) 5 return HttpResponse(temp)