标签:
function ajax(method, url, data, success) { //success是一个回调函数 var xhr = null; try { xhr = new XMLHttpRequest(); } catch (e) { xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘); } if (method == ‘get‘ && data) { //url在get方式的时候是可变的;如果有data存在并且方法是get的时候 url += ‘?‘ + data; } xhr.open(method,url,true); if (method == ‘get‘) { xhr.send(); } else { xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘); //POST方式在send之前,要设置请求头,告知文档类型 xhr.send(data); } xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { success && success(xhr.responseText); //如果success存在的话就执行函数 } else { alert(‘出错了,Err:‘ + xhr.status); } } } }
oBtn.onclick = function() { ajax(‘get‘,‘getNews.php‘,‘‘,function(data) { var data = JSON.parse( data ); //转换 var oUl = document.getElementById(‘ul1‘); var html = ‘‘; for (var i=0; i<data.length; i++) { html += ‘<li><a href="">‘+data[i].title+‘</a> [<span>‘+data[i].date+‘</span>]</li>‘; } oUl.innerHTML = html; }); setInterval(function() { //定时刷新获取数据 ajax(‘get‘,‘getNews.php‘,‘‘,function(data) { var data = JSON.parse( data ); var oUl = document.getElementById(‘ul1‘); var html = ‘‘; for (var i=0; i<data.length; i++) { html += ‘<li><a href="">‘+data[i].title+‘</a> [<span>‘+data[i].date+‘</span>]</li>‘; } oUl.innerHTML = html; }); }, 1000); }
标签:
原文地址:http://www.cnblogs.com/webcome/p/5426538.html