ajax无刷新异步传输
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax</title> <style> #btn{ width: 120px; background-color: #ff4500; color: #ffffff; line-height: 30px; cursor: pointer; text-align: center; margin-bottom: 10px; } #aStrList{ border:1px solid #d0d0d0; padding: 20px; } #aStrList p{ display: block; height: 30px; overflow: hidden; border-bottom: 1px solid #ff4500; } #aStrList p span{ float: left; width: 100px; line-height: 30px; } </style> </head> <body> <div id="btn">Ajax button</div> <div id="aStrList"> <p> <span>Lily</span> <span>female</span> <span>21</span> </p> </div> <script> window.onload = function(){ var oBtn = document.getElementById("btn"); var olist = document.getElementById("aStrList"); oBtn.onclick = function(){ ajax("data.php?t="+new Date().getTime(),function(str){//success var aStr = eval(str); for(var i=0; i<aStr.length; i++){ var newItem = document.createElement("p"); for(var j=0; j<aStr[i].length; j++){ var newItemSpan = document.createElement("span"); newItemSpan.innerHTML += aStr[i][j]; newItem.appendChild(newItemSpan); } olist.appendChild(newItem); } },function(failedstr){//failed olist.innerHTML = failedstr; }) } } //ajax function ajax(url,fnSuccess,fnFailed){ //1.create ajax object if(window.XMLHttpRequest){ var oAjax = new XMLHttpRequest; }else{ var oAjax = new ActiveXobject("Microsoft.XMLHTTP"); } //2.connect webservice(method,file,asynchronous) oAjax.open("GET",url,true); //3.send oAjax.send(); //4.receive oAjax.onreadystatechange = function(){ if(oAjax.readyState==4){ if(oAjax.status==200){ fnSuccess(oAjax.responseText); }else{ if(fnFailed){ fnFailed(oAjax.status); } } } } } </script> </body> </html>
data.php
[ ["Jame","male","23"], ["Lucy","female","18"], ["Jack","male","25"] ]