Javascript Ajax实例
HTML文件:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>传统的Ajax方式与服务端交互</title> <style> .frame{width:250px;height: auto;overflow: hidden;margin:0 auto;} .frame ul li{height:40px;line-height: 40px;display: block;border-bottom: 1px solid #ccc;} .frame ul li span{padding:10px;} </style> </head> <body> <div class="frame"> <ul id="stuinfo"> <li>正在加载中...</li> </ul> </div> <script> (function(){ var xhr=null; if(window.ActiveXObject){ xhr=new ActiveXObject('Microsoft.XMLHTTP'); }else if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); } xhr.open('GET','stu.php',true); xhr.send(null); xhr.onreadystatechange=function(){ switch(xhr.readyState){ case 0: document.getElementById('stuinfo').innerHTML='未初始化...'; console.log(0,'未初始化...'); break; case 1: document.getElementById('stuinfo').innerHTML='请求参数已准备,尚未发送请求...'; console.log(1,'请求参数已准备,尚未发送请求...'); break; case 2: document.getElementById('stuinfo').innerHTML='已经发送请求,尚未接收响应...'; console.log(2,'已经发送请求,尚未接收响应..'); break; case 3: document.getElementById('stuinfo').innerHTML='正在接受部分响应...'; console.log(3,"正在接受部分响应..."); break; case 4: document.getElementById('stuinfo').innerHTML='响应全部接受完毕...'; console.log(4,"响应全部接受完毕..."); break; }; if(xhr.readyState==4 && xhr.status==200) { var HTML=''; var data=eval("("+xhr.responseText+")"); for(var i=0;i<data.length;i++){ HTML+="<li><span>"+data[i].code+"</span>"; HTML+="<span>"+data[i].name+"</span>"; HTML+="<span>"+data[i].score+"</span></li>"; } document.getElementById('stuinfo').innerHTML=HTML; } } })(); </script> </body> </html>
PHP文件:
<?php header("Content-type:text/json"); $stulist=array( array("code"=>"10101","name"=>"刘真真","score"=>"530"), array("code"=>"10102","name"=>"张明基","score"=>"530"), array("code"=>"10103","name"=>"舒观","score"=>"530"), array("code"=>"10104","name"=>"周小敏","score"=>"530"), array("code"=>"10105","name"=>"陆明明","score"=>"530"), array("code"=>"10106","name"=>"杨真","score"=>"530"), array("code"=>"10107","name"=>"黄小芳","score"=>"530"), array("code"=>"10108","name"=>"张佳","score"=>"530"), ); echo json_encode($stulist); ?>
寅春树:爱设计,爱前端,更爱程序
QQ:41676015