需求: 每秒鐘請求一次服務器 獲取到數據javascript
實現: 把ajax進行封裝php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="ajax.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> window.onload = function(){ var oBtn = document.getElementById("btn"); oBtn.onclick = function(){ setInterval(function(){ ajax("get",'getData.php','',function(data){ var oUl = document.getElementById('ul1'); var html = '' for(var i = 0; i < data.length; i++) { var oli = document.createElement('li'); html += '<li>'+ data[i].title + '[' + data[i].time + ']</li>'; } oUl.innerHTML = html; }); },1000) } } </script> </head> <body> <input type="button" id="btn" value="獲取數據" /> <ul id="ul1"> </ul> </body> </html>
function ajax(method,url,data,sucess) { //建立ajax對象 var xhr = null; try { xhr = new XMLHttpRequest(); } catch(e) { xhr = new ActiveXobject('Microsoft.XMLHTTP'); } if(!method || method == "get"){ method = "get"; //打開要獲取文件的地址 if(data){ url = url+"?"+data; } xhr.open(method, url, true); //發送請求 xhr.send(); }else{ method = "post"; xhr.open(method, url, true); if(data){ //發送請求 xhr.send(); }else{ xhr.send(data); } } //alert(xhr.responseText); //監聽請求狀態 xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); sucess && sucess(); } } }
function ajax(obj) { //建立ajax對象 var xhr = null; try { xhr = new XMLHttpRequest(); } catch(e) { xhr = new ActiveXobject('Microsoft.XMLHTTP'); } if(!obj.method || obj.method == "get"){ obj.method = "get"; //打開要獲取文件的地址 if(obj.data){ obj.url = obj.url+"?"+obj.data; } xhr.open(obj.method, obj.url, true); //發送請求 xhr.send(); }else{ obj.method = "post"; xhr.open(obj.method, obj.url, true); if(data){ //發送請求 xhr.send(); }else{ xhr.send(obj.data); } } //alert(xhr.responseText); //監聽請求狀態 xhr.onreadystatechange = function() { if(xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); obj.success && obj.success(data); } } }