Ajax
原生Ajax
基于XMLHttpRequest对象
// 跨浏览器支持/*XmlHttpRequestIE7+, Firefox, Chrome, Opera, etc.ActiveXObject("Microsoft.XMLHTTP")IE6, IE5*/function GetXHR(){var xhr = null;if(XMLHttpRequest){xhr = new XMLHttpRequest();}else{xhr = new ActiveXObject("Microsoft.XMLHTTP");}return xhr;}// post请求function XhrPostRequest(){var xhr = GetXHR();var formData = new FormData();formData.append('k1', 'v1');// 定义回调函数xhr.onreadystatechange = function(){if(xhr.readyState == 4){// 已经接收到全部响应数据,执行以下操作var data = xhr.responseText;console.log(data);}};// 指定连接方式和地址----文件方式xhr.open('POST', "/test/", true);// 设置请求头// 使用FormData对象不用加该请求头xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');// 发送请求xhr.send('n1=1;n2=2;');// formDataxhr.send(formData)}// get请求function XhrGetRequest(){var xhr = GetXHR();// 定义回调函数xhr.onreadystatechange = function(){if(xhr.readyState == 4){// 已经接收到全部响应数据,执行以下操作var data = xhr.responseText;console.log(data);}};// 指定连接方式和地址----文件方式xhr.open('get', "/test/", true);// 发送请求xhr.send();}
jQuery Ajax
内部基于原生Ajax
$.ajax({url: '',type: 'POST',data: {'a1': '', 'a2': ''}success: function(res){}})
伪Ajax
- 非XMLHttpRequest
<iframe>标签,不刷新发送http请求
<form id='f1' method='POST' action='' target='ifr'><iframe id='ifr' name='ifr' style='display:none'></iframe><input type='text' name='user'><a onclick='submitForm()'>提交</a></form><script>function submitForm(){document.getElementById('ifr').onload=loadIframe;document.getElementById('f1').submit();}function loadIframe(){var content = document.getElementById('ifr').contentWindow.document.body.innerText;}</script>
Ajax跨域,JSONP
只能发送get请求
Ajax:访问其他域名URL被阻止
浏览器:同源策略
- 禁止:Ajax跨域发送请求时,再回来时浏览器拒绝接受
- 允许:script标签没有禁止
<button onclick='send()'>发送</button><script>function list(arg){console.log(arg);}function send(){var tag = document.createElement('script');tag.src = 'http://xxxxxx?callback=list';// http://xxxxxx 返回是数据必须是 liat(数据);这个格式document.head.appendElement(tag);}</script>
jQuery Jsonp
$.ajax({url: 'xxx',type:'GET',dataType: 'JSONP',jsonp: 'callback',jsonpCallback: 'list',})function list(args){console.log(args);}
CORS
可以发任何请求
简单请求
请求方式:HEAD、GET、POST
添加响应头 Access-Control-Allow-Origin
obj = HttpResponse()obj['Access-Control-Allow-Origin'] = 'http://xxx.xx' # 允许指定的域名obj['Access-Control-Allow-Origin'] = '*' # 允许的所有域名
复杂请求
复杂请求需要先预检
if request.method == 'OPTIONS':obj = HttpResponse()obj['Access-Control-Allow-Origin'] = '*'obj['Access-Control-Allow-Methods'] = 'DELETE' # 允许DELETE请求return objobj = HttpResponse('xxx')obj['Access-Control-Allow-Origin'] = '*'return obj
Ajax 上传文件
XMLHttpRequest
<input type='file' id='f1'/><a onclick='upload1()'>XMLHttpRequest上传</a><a onclick='upload2()'>jQuery上传</a><script>function upload1(){var formData = new FormData();formData.append('k1', 'v1');// jQuery 转 document$('#f1')[0] // jQuery 对象 取第0个元素就是document对象//document 转 jQuery$(document.getElementById('f1')) // document 加$formData.append('imgFile', $('#f1')[0].files[0]);var xhr = new XMLHttpRequest();xhr.onreadystatechange = function(){if(xhr.readyState == 4){// 等到返回的路径var file_path = xhr.responseText;}}xhr.open('POST', '/upload/');xhr.send(formData);}function upload2(){var formData = new FormData();formData.append('k1', 'v1');formData.append('imgFile', document.getElementById('f1').files[0]);$.ajax({url:'/upload/',type:'POST',data: formData,// 使用FormData需要告诉jQuery对数据无需处理contentType:false,processData:false,success: function(arg){}})}</script>
伪Ajax
兼容性更好
<form id='form1' method='POST' action='/upload/' target='ifr' enctype='multipart/form-data'><iframe id='ifr' name='ifr' style='display:none'></iframe><input typpe='file' name='img' /><button onclick='upload()'>上传</button></form><script>function upload(){document.getElementById('ifr').onload=loadIframe;document.getElementById('f1').submit();}function loadIframe(){var content = document.getElementById('ifr').contentWindow.document.body.innerText;}</script>
图片预览
ajax上传预览
- 将图片上传到临时文件夹中, 返回url
- 提交时将图片拷贝到存放目录中
本地预览
// 只有高级浏览器支持var obj = $(this)[0].files[0];var v = window.URL.createObjectURL(obj);$('#img').attr('src', v);//需要手动释放$('#img').load(function(){window.URL.revokeObjectURL(v); // 手动释放,需要图片在页面上显示后再释放}//-------// 会自动释放内存var reader = newFileReader()reader.readAsDataFile(obj)reader.onload = function(e){$('#img').attr('src', this.result)}
XMLHttpRequest对象
主要方法
void open(String method, String url, Boolean async)用于创建请求参数:method: 请求方式(String),如'POST','GET','DELETE'...url: 要请求的地址(String)async: 是否异步(Boolean)void send(String body)用于发送请求参数:body:要发送的数据(String)void setRequestHeader(String header, String Value)用于设置请求头参数:header:请求头的key(String)value: 请求头的value(String)String getAllResponseHeaders()获取所有响应头返回值:响应头数据(String)String getResponseHeader(String header)获取响应头中指定header的值参数:header: 响应头的key(String)返回值:响应头中指定的header对应的值void abort()终止请求
主要属性
Number readyState状态值(整数)0 未初始化, 尚未调用open()方法1 启动, 调用了open()方法,未调用send()方法2 发送,已经调用send()方法,未接收到响应3 接收,已经接收到部分响应数据4 完成,已经接收到全部响应数据Function onreadystatechange当redayState的值改变时自动触发执行其对于的函数(回调函数)String responseText服务器返回的数据(String)XmlDocument responseXML服务器返回的数据(Xml对象)Number states状态码,如 200, 404...String statesText状态文本
