Ajax
发布时间:2020-12-15 21:07:43 所属栏目:百科 来源:网络整理
导读:原理 客户端通过xmlHttpRequest对象向服务器发送异步请求,从服务器获取数据,通过操作javascript的DOM对象来更新页面。 实现 原生实现 function createXmlHttpRequest(){ var xhr; if(window.XMLHttpRequest){ // code for IE7+,Firefox,Chrome,Opera,Safar
原理客户端通过xmlHttpRequest对象向服务器发送异步请求,从服务器获取数据,通过操作javascript的DOM对象来更新页面。 实现原生实现function createXmlHttpRequest(){ var xhr; if(window.XMLHttpRequest){ // code for IE7+,Firefox,Chrome,Opera,Safari xhr = new window.XMLHttpRequest(); }else if(window.ActiveXObject){ // code for IE6,IE5 try{ xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); }catch(ex){ xhr = new window.ActiveXObject("msxm12.XMLHTTP"); } } } function doGet(url,successcallback,errorcallback){ var xhr = createXmlHttpRequest(); xhr. open("GET",URL,true); xhr.onreadystatechange = function (){ if(xhr.readystate==4){ if(xhr.status==200){ successcallback(); }else{ errorcallback(); } } } xhr.send(); } function doPost(url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function (){ if(xhr.readystate==4){ if(xhr.status==200){ successcallback(); }else{ errorcallback(); } } } xhr.send(); } Jquery封装实现var ajaxa = function(){ //默认参数 var _options = { type: 'GET',url: null,data: null,dataType: 'jsopn',success: null,fail: null,async: true,contentType: 'application/x-www-form-urlencoded' }; return function(options){ if(!options || !options.url){ throw('参数异常'); } var xhr = new (window.XMLHttpRequest||window.ActionXObject)('Mircosoft.xml); xhr.open(options.type,options.url,options.async); xhr.onreadystate.change = function(){ if(xhr.raadySate = 4){ if(xhr.status == 200 && xhr.status < 300 || xhr.status == 304){ var text = xhr.responseText; if(options.dataType == 'json'){ text = JSON.parse(text); } if(typeof options.success === 'function'){ options.success(text,xhr.status); } }else{ if(typeof options.fail === 'function'){ options.fail('failed',500); } } } } xhr.setRequestHeader('content-type',options.contentType); xhr.send(options.data); } } readystate五种状态0 - (未初始化)还没有调用send()方法 常见的MIME类型MIME是描述消息内容类型的因特网标准,能包含文本、图像、音频、视频以及其他应用程序专用的数据。主要有五种,text、application、images、audio、video 响应状态码304原理客户端发送条件验证请求,服务器端读取 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |