jquery框架的ajax方法虽然好用,但是如果我们的项目需求简单,交互功能少,引入jquery会造成页面臃肿。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ems</title> <style type="text/css"> #ems{ position: absolute; left: 50%; width: 400px; height: auto; margin-left: -200px; background: lightGreen; text-align: center; min-height: 50px; height: 500px; overflow-y: scroll; overflow-x: hidden; } #ems input{ height: 25px; margin-top: 10px; } #list{ background: lightBlue; } #list li{ text-align: left; } </style> </head> <body> <div id="ems"> <div> <input type="text" id="code"> <input type="button" value="查询" id="btn"> </div> <div id="list"> </div> </div> <script type="text/javascript"> function ajax(data) { //我们封装的函数为了能实现可传入无限多个参数,在我们即将封装函数时,需要使用对象进行传参 //data = {data:"",dataType:"xml/json",type:"get/post",url:"",asyn:"true/false",success:function(){},filure:function(){}} // //data:{username:123,password:456} 发送的参数形式,用这种形式需要转换,所以用下面的字符串拼接的形式 //data = ‘username=123&password=456‘; //第一步:创建xhr对象 var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘); } //第二步:准备发送前的一些配置参数 var type = data.type == ‘get‘?‘get‘:‘post‘; var url =‘‘; if(data.url){ url = data.url; if(type == ‘get‘){ url += "?" + data.data + "&_t=" + new Date().getTime(); } } var flag = data.asyn == ‘true‘?‘true‘:‘false‘; xhr.open(type,url,flag); //第三步:执行发送的动作 if(type == ‘get‘){ xhr.send(null); }else if(type == ‘post‘){ xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(data.data); } //第四步:指定回调函数 xhr.onreadystatechange = function () { if(this.readyState == 4){ if(this.status == 200){ if(typeof data.success == ‘function‘){ var d = data.dataType == ‘xml‘?xhr.responseXML:xhr.responseText; data.success(d); } }else{ if(typeof data.failure == ‘function‘) { data.failure(); } } } } } window.onload = function () { var btn = document.getElementById(‘btn‘); btn.onclick = function () { var code = document.getElementById(‘code‘).value; if(!code){ document.getElementById(‘list‘).innerHTML = "请输入查询单号"; return; } var param = { data:‘code=‘+code, url:‘07ems.php‘, type:‘get‘, dataType:‘json‘, success:function(data){ var data = JSON.parse(data); if(data.status == 0){ var list = data.data.info.context; // console.log(list); var tag = ‘‘; for(var i=0;i<list.length;i++){ // console.log(list[i]); var item = list[i]; var desc = item.desc; var t = new Date(); t.setTime(item.time +‘000‘); var str = t.getFullYear()+‘年‘+(t.getMonth()+1)+‘月‘+t.getDay()+‘日‘+(t.getHours()>12?‘ 下午‘:‘ 上午‘)+t.getHours()%12+‘:‘+t.getMinutes()+‘:‘+t.getSeconds(); tag += ‘<li><div>‘+str + ‘</div><div>‘ + desc+‘</div></li>‘ } var ul = document.createElement(‘ul‘); ul.innerHTML = tag; document.getElementById(‘list‘).appendChild(ul); }else{ var info = data.msg; document.getElementById(‘list‘).innerHTML = info; } } }; ajax(param); } } </script> </body> </html>