原生Ajax 和jQuery Ajax的区别示例分析
前言:这次介绍的是利用ajax与后台进行数据交换的小例子,所以demo必须通过服务器来打开。服务器环境非常好搭建,从网上下载wamp或xampp,一步步安装就ok,然后再把写好的页面放在服务器中指定的位置。打开时,在浏览器地址栏输入“localhost/指定页面”或者“127.0.0.1/指定页面”打开。
下面列出demo的HTML、PHP、原生ajax、jqajax代码。
HTML代码:
<!doctypehtml> <html> <head> <title>ajax示例</title> <metacharset='utf-8'/> <linkrel="stylesheet"type="text/css"href="css/common.css"/> <styletype="text/css"> .main{height:400px;width:800px;margin:100pxauto0;border:1pxsolid#000;} .list{height:400px;width:200px;float:left;background:#ddd;} .inf{height:400px;width:600px;float:right;background:#ccc;text-align:center;} .listli{width:200px;text-align:center;margin:50px00;font-size:24px;cursor:pointer; } .infimg{width:360px;height:270px;margin:15pxauto;} .infp{width:580px;text-align:left;text-indent:2em;font-size:14px;margin:010px;} </style> </head> <body> <divclass='main'> <divclass='list'id='list'> <ul> <liname='spring'id='spring'>春</li> <liname='summer'id='summer'>夏</li> <liname='fall'id='fall'>秋</li> <liname='winter'id='winter'>冬</li> </ul> </div> <divclass='inf'id='inf'> <!--要插入的内容--> </div> </div> </body> <scripttype="text/javascript"charset="utf-8"src="js/jQuery.js"></script> </html>
PHP代码:
<?php $details=array( 'spring' => "<imgsrc='images/spring.jpg'alt=''/><p>人间四月芳菲尽,山寺桃花始盛开</p>", 'summer' => "<imgsrc='images/summer.jpg'alt=''/><p>水晶帘动微风起,满架蔷薇一院香</p>", 'fall' => "<imgsrc='images/fall.jpg'alt=''/><p>金井梧桐秋叶黄,珠帘不卷夜来霜</p>", 'winter' => "<imgsrc='images/winter.jpg'alt=''/><p>梅须逊雪三分白,雪却输梅一段香</p>" ); echo$details[$_REQUEST['LiName']]; ?>
原生ajax:
<scripttype="text/javascript"> varlis=document.getElementById('list').getElementsByTagName('li'); window.onload=initPage; functioninitPage(){ for(vari=0;i<lis.length;i++){ txt=lis[i]; txt.onclick=function(){ getDetails(this.id); } } } functioncreatRequest(){ try{ request=newXMLHttpRequest(); } catch(tryMS){ try{ request=newActiveXObject("Msxml2.XMLHTTP"); } catch(otherMS){ try{ request=newActiveXObject("Miscrosoft.XMLHTTP"); } catch(failed){ request=null; } } } returnrequest; } functiongetDetails(itemName){ request=creatRequest(); if(request==null){ alert('没有成功创建请求') return; } varurl="getDetails.php?LiName="+escape(itemName); request.open("GET",url,true); request.onreadystatechange=displayDetails; request.send(null); } functiondisplayDetails(){ if(request.readyState==4){ if(request.status==200){ detailDiv=document.getElementById("inf"); detailDiv.innerHTML=request.responseText; } } } </script>
JQajax:
<scripttype="text/javascript"> $('#listli').click(function(){ $.ajax({ type:'GET', data:'', url:"getDetails.php?LiName="+this.id, success:function(data){ $('#inf').html(data); }, dataType:'text', error:function(){ alert("失败!"); } }) }); </script>