参考老师博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html
一,原生Ajax
Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。
JQuery提供的Ajax方法:
$.ajax({ ???url: , ???type: ‘‘, ???dataType: ‘‘, ???data: { ?????????????}, ???success: function(){ ????????????}, ???error: function(){ ?????????????} })
一般来说,大家可能都会习惯用JQuery提供的Ajax方法,但是用原生的js怎么去实现Ajax方法呢?
Ajax的实现主要分为四部分:
1、创建Ajax对象
// 创建ajax对象var xhr = null;if(window.XMLHttpRequest){ ???xhr = new XMLHttpRequest(); ?//// XMLHttpRequest对象用于在后台与服务器交换数据} else { ???//为了兼容IE6 ???xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘);}
2、连接服务器
// 连接服务器open(方法GET/POST,请求地址, 异步传输)xhr.open(‘GET‘, ?‘data.txt‘, ?true);
说明:open(method, url, async) 方法需要三个参数:
method:发送请求所使用的方法(GET或POST);与POST相比,GET更简单更快,并且在大部分情况下都能用;然而,在以下情况中,请使用POST
- 无法使用缓存文件(更新服务器上的文件或数据库)
- 向服务器发送大量数据(POST 没有数据量限制)
- 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
url:规定服务器端脚本的 URL(该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务));
async:规定应当对请求进行异步(true)或同步(false)处理;true是在等待服务器响应时执行其他脚本,当响应就绪后对响应进行处理;false是等待服务器响应再执行。
3、发送请求,将请求送往服务器。
// 发送请求xhr.send();
4、接收返回数据
// 处理返回数据/*** 每当readyState改变时,就会触发onreadystatechange事件** readyState属性存储有XMLHttpRequest的状态信息,存有服务器响应的状态信息。
** onreadystatechange:存有处理服务器响应的函数,每当 readyState 改变时,onreadystatechange 函数就会被执行。** 0 :请求未初始化** 1 :服务器连接已建立** 2 :请求已接受** 3 : 请求处理中** 4 :请求已完成,且相应就绪*/xhr.onreadystatechange = function(){ ???if(xhr.readyState == 4){ ???????/* ???????** Http状态码 ???????** 1xx :信息展示 ???????** 2xx :成功 ???????** 3xx :重定向 ???????** 4xx : 客户端错误 ???????** 5xx :服务器端错误 ???????*/ ???????if(xhr.status == 200){ ???????????success(xhr.responseText); ?//获得字符串形式的响应数据。 ???????} else { ???????????if(failed){ ???????????????failed(xhr.status); ???????????} ???????} ???}}
5.Ajax封装函数示例:
function Ajax(type, url, data, success, failed){ ???// 创建ajax对象 ???var xhr = null; ???if(window.XMLHttpRequest){ ???????xhr = new XMLHttpRequest(); ???} else { ???????xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘) ???} ????var type = type.toUpperCase(); ???// 用于清除缓存 ???var random = Math.random(); ????if(typeof data == ‘object‘){ ???????var str = ‘‘; ???????for(var key in data){ ???????????str += key+‘=‘+data[key]+‘&‘; ???????} ???????data = str.replace(/&$/, ‘‘); ???} ????if(type == ‘GET‘){ ???????if(data){ ???????????xhr.open(‘GET‘, url + ‘?‘ + data, true); ???????} else { ???????????xhr.open(‘GET‘, url + ‘?t=‘ + random, true); ???????} ???????xhr.send(); ????} else if(type == ‘POST‘){ ???????xhr.open(‘POST‘, url, true); ???????// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。 ???????xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ???????xhr.send(data); ???} ????// 处理返回数据 ???xhr.onreadystatechange = function(){ ???????if(xhr.readyState == 4){ ???????????if(xhr.status == 200){ ???????????????success(xhr.responseText); ???????????} else { ???????????????if(failed){ ???????????????????failed(xhr.status); ???????????????} ???????????} ???????} ???}} // 测试调用var sendData = {name:‘asher‘,sex:‘male‘};Ajax(‘get‘, ‘data/data.html‘, sendData, function(data){ ???console.log(data);}, function(error){ ???console.log(error);});
1、XmlHttpRequest对象介绍
什么是 XMLHttpRequest 对象?
XMLHttpRequest 对象用于在后台与服务器交换数据。XMLHttpRequest 对象是开发者的梦想,因为您能够:
- 在不重新加载页面的情况下更新网页
- 在页面已加载后从服务器请求数据
- 在页面已加载后从服务器接收数据
- 在后台向服务器发送数据
所有现代的浏览器都支持 XMLHttpRequest 对象。
1.1 XmlHttpRequest对象的主要方法:
a. void open(String method,String url,Boolen async) ??用于创建请求 ??????参数: ??????method: 请求方式(字符串类型),如:POST、GET、DELETE... ??????url: ???要请求的地址(字符串类型) ??????async: ?是否异步(布尔类型) b. void send(String body) ???用于发送请求 ????参数: ???????body: 要发送的数据(字符串类型) c. void setRequestHeader(String header,String value) ???用于设置请求头 ????参数: ???????header: 请求头的key(字符串类型) ???????vlaue: ?请求头的value(字符串类型) d. String getAllResponseHeaders() ???获取所有响应头 ????返回值: ???????响应头数据(字符串类型) e. String getResponseHeader(String header) ???获取响应头中指定header的值 ????参数: ???????header: 响应头的key(字符串类型) ????返回值: ???????响应头中指定的header对应的值 f. void abort() ????终止请求
1.2. XMLHttprequest对象来发生原生Ajax数据的示例
views.py
def ajax(request): ???return render(request,‘ajax.html‘)
Ajax.html
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body> ???<input type="button" value="Ajax1" onclick="Ajax1();"/> ???<script> ???????function Ajax1(){ ???????????var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象 ???????????xhr.open(‘GET‘,‘/index/‘,true); //指定用什么形式发,发到哪里,是否异步(是) ???????????xhr.send("name=root;pwd=123"); //发送的数据 ???????} ???</script></body></html>
页面效果:
1.3 不往Ajax页面发了,往ajax_json处发。修改程序
views.py
def ajax(request): ???return render(request,‘ajax.html‘)def ajax_json(request): ???ret={‘status‘:True,‘data‘:None} #字典 ???import json ???return HttpResponse(json.dumps(ret))
ajax.html
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body> ???<input type="text"/> ???<input type="button" value="Ajax1" onclick="Ajax1();"/> ???<script> ???????function Ajax1(){ ???????????var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象 ???????????xhr.open(‘GET‘,‘/ajax_json/‘,true); //指定用什么形式发,发到哪里,是否异步(是) ???????????xhr.send("name=root;pwd=123"); //发送的数据 ???????} ???</script></body></html>
urls.py
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ ???url(r‘^admin/‘, admin.site.urls), ???url(r‘^index/‘, views.index), ???url(r‘^user_list/‘, views.user_list), ???url(r‘^edit-(\d+)/‘, views.user_edit), ???url(r‘^ajax/$‘, views.ajax), ???url(r‘^ajax_json/$‘, views.ajax_json), ???url(r‘^orm/‘, views.orm),]
访问页面
1.4 XmlHttpRequest对象的主要属性:
a. Number readyState ??状态值(整数) ???详细: ?????0-未初始化,尚未调用open()方法; ?????1-启动,调用了open()方法,未调用send()方法; ?????2-发送,已经调用了send()方法,未接收到响应; ?????3-接收,已经接收到部分响应数据; ?????4-完成,已经接收到全部响应数据; b. Function onreadystatechange ?#回调函数 ??当readyState的值改变时自动触发执行其对应的函数(回调函数) c. String responseText ??服务器返回的数据(字符串类型) d. XmlDocument responseXML ??服务器返回的数据(Xml对象) e. Number states ??状态码(整数),如:200、404... f. String statesText ??状态文本(字符串),如:OK、NotFound...
1.5 在前端页面上拿到返回值。
ajax.html
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body> ???<input type="text"/> ???<input type="button" value="Ajax1" onclick="Ajax1();"/> ???<script> ???????function Ajax1(){ ???????????var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象 ???????????xhr.open(‘GET‘,‘/ajax_json/‘,true); //指定用什么形式发,发到哪里,是否异步(是) ???????????xhr.onreadystatechange=function(){ ???????????????if(xhr.readyState==4){ ???????????????????//接收完毕,放到XMLHttprequest对象里面了 ???????????????????console.log(xhr.responseText); ???????????????} ???????????}; ???????????xhr.send("name=root;pwd=123"); //发送的数据 ???????} ???</script></body></html>
1.6 返回状态码
def ajax(request): ???return render(request,‘ajax.html‘)def ajax_json(request): ???ret={‘status‘:True,‘data‘:None} #字典 ???import json ???return HttpResponse(json.dumps(ret),status=404,reason=‘Not Found‘)
1.7 代码保存,发生GET请求
ajax.html
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body> ???<input type="text"/> ???<input type="button" value="Ajax1" onclick="Ajax1();"/> ???<script> ???????function Ajax1(){ ???????????var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象 ???????????xhr.open(‘GET‘,‘/ajax_json/‘,true); //指定用什么形式发,发到哪里,是否异步(是) ???????????xhr.onreadystatechange=function(){ ???????????????if(xhr.readyState==4){ ???????????????????//接收完毕,放到XMLHttprequest对象里面了 ???????????????????var obj=JSON.parse(xhr.responseText); ???????????????????console.log(obj); ???????????????} ???????????}; ???????????xhr.setRequestHeader(‘k1‘,‘v1‘); //发送的时候带着请求头,csrf的时候用。 ???????????xhr.send("name=root;pwd=123"); //发送的数据 ???????} ???</script></body></html>
views.py
def ajax(request): ???return render(request,‘ajax.html‘)def ajax_json(request): ???ret={‘status‘:True,‘data‘:None} #字典 ???import json ???return HttpResponse(json.dumps(ret),status=404,reason=‘Not Found‘)
1.8 用原生的Ajax发送POST请求:一定要记住需要设置请求头。
views.py
def ajax(request): ???return render(request,‘ajax.html‘)def ajax_json(request): ???print(request.POST) ???ret={‘status‘:True,‘data‘:None} #字典 ???import json ???return HttpResponse(json.dumps(ret),status=404,reason=‘Not Found‘)
Ajax.html
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title></head><body> ???<input type="text"/> ???<input type="button" value="Ajax1" onclick="Ajax1();"/> ???<script> ???????function Ajax1(){ ???????????var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象 ???????????xhr.open(‘POST‘,‘/ajax_json/‘,true); //指定用什么形式发,发到哪里,是否异步(是) ???????????xhr.onreadystatechange=function(){ ???????????????if(xhr.readyState==4){ ???????????????????//接收完毕,放到XMLHttprequest对象里面了 ???????????????????var obj=JSON.parse(xhr.responseText); ???????????????????console.log(obj); ???????????????} ???????????}; ???????????xhr.setRequestHeader(‘k1‘,‘v1‘); //发送的时候带着请求头,csrf的时候用。 ???????????xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded; charset-UTF-8‘); ???????????//设置请求头,判断发来的请求头里面,怎么样把数据打包的。这样后台就知道怎么样去解了。 ???????????xhr.send("name=root;pwd=123"); //发送的数据 ???????} ???</script></body></html>
效果:
1.9, 浏览器的兼容性问题
var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
二,jQuery的Ajax
Day24-Ajax
原文地址:http://www.cnblogs.com/momo8238/p/7763556.html