对理解ajax第三个回调函数的封装和 null设置少传的那个参数默认
<script>
var a=function(msg){ alert( msg); } a(1); </script>
之前看视频对ajax封装回调函数总不太理解,知道上边例子跑通就理解了一个函数作为参数,其实函数后边再加括号里边传入参数也可以运行,像这样自调用匿名函数 <script> 还有可以利用null设置少传的那个参数默认是什么 <script> (function() { //获取dom元素 var$ = function(id) { returndocument.getElementById(id); }; //返回对应的Ajax对象 做兼容性处理 $.init= function() { try{ returnnew XMLHttpRequest(); }catch (e) { } try{ returnnew ActiveXObject('Microsoft.XMLHTTP'); }catch (e) { } }; //Ajax的get请求 $.get= function(url,data,callback,type) { //url:请求地址 //data:请求参数 //callback:回调函数 //创建对象 varxhr = $.init(); //添加时间戳解决缓存问题 url= url + '?_=' + new Date().getTime(); //如果传递参数,则连接参数字符串 if(data != null) { url= url + '&' + data; } //初始化Ajax对象 xhr.open('get',url); //回调函数 xhr.onreadystatechange= function() { if(xhr.readyState == 4 && xhr.status == 200) { //当接收数据完毕后,调用指定的函数,将ajax对象 //的返回值做为参数进行传递 if(type == null) { type= 'text'; } if(type == 'text') { callback(xhr.responseText); } if(type == 'xml') { callback(xhr.responseXML); } if(type == 'json') { callback(eval('('+ xhr.responseText + ')')) } } }; //发送Ajax请求 xhr.send(null); }; //Ajax的post请求 $.post= function(url,callback,type) { varxhr = $.init(); xhr.open('post',url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange= function() { if(xhr.readyState == 4 && xhr.status == 200) { if(type == null) { type= 'text'; } if(type == 'text') { callback(xhr.responseText); } if(type == 'xml') { callback(xhr.responseXML); } if(type == 'json') { callback(eval('('+ xhr.responseText + ')')) } } }; xhr.send(data); }; window.$ = $; })();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |