模仿jQuery中ajax的功能。自己封装了一个简单的ajax实现函数。用来练手的,里面没有考虑安全性问题。
ajax.js
/** * Date 2012-11-3 * */ function ajax(options){ /** *创建xmlHttpRequest对象 *对于不同的浏览创建xmlHttpRequest的对象所使用的方法不同 * */ var xmlHttp=null; if(typeof(xmlHttp)=="undefined" || xmlHttp==null){ try{ xmlHttp = new XMLHttpRequest(); }catch(e1){ try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e2){ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } } } /** create END **/ /** *属性参数,先写几个作为测试,以后会陆续增加 */ var default_options={ url:"", method:"GET", async:true, data:"", success:"", }; /** 属性 END **/ //判断请求中是否带有url参数,没有的话则不给处理 if(typeof(options.url)=='undefined' || options.url==""){ alert("调用ajax请求时,url不能为空!!"); return; } //如果请求方式也没写的话,则使用默认的设置 if(typeof(options.method)=='undefined' || options.method==""){ options.method=default_options.method; } //请求模式为空使用默认设置,默认使用异步请求 if(typeof(options.async)=='undefined' || options.async==""){ options.async=default_options.async; } /** *请求参数,get方式与post方式请求发送参数的方式不同。如果是get方式直接 *将参数连接到url后面 */ if(options.method.toLowerCase()=="get"){ if(typeof(options.data)!='undefined' && options.data!="" && options.data!=null){ options.url+="?"+options.data; } } //连接服务器 xmlHttp.open(options.method,options.url,options.async); //发送请求的数据 GET方式与post方式请求时传送参数的方式不同。分开对待 if(options.method.toLowerCase()=="post"){ xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send(options.data); }else{ xmlHttp.send(null); } //异步请求状态发生改变时,执行的函数 eval(options.success); xmlHttp.onreadystatechange=function(){ //readyState==4请求已完成 status==200服务器响应完成 if(xmlHttp.readyState==4 && xmlHttp.status==200){ //执行响应的结果 eval(options.success(xmlHttp.responseText)); xmlHttp=null; } } }
测试代码Test.html
<html> <head> <script type="text/javascript" src="js/ajax.js"></script> <script type="text/javascript"> function load(){ /*createXmlHttpRequest(); open("GET","ajax.php",false,"showResult()"); */ ajax({ url:"ajax.php", method:"POST", data:"username=M1&password=P1", success:function(msg){ alert(msg); } }); } </script> </head> <body onload="load();"> </body> </html>