初探ajax
作用:不重新加载整个页面,却能获取到新的网页所需的数据和更新部分网页内容
调用方式
var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } console.log(xhr.readyState); xhr.open('GET','http://localhost/network/class7.../xx.php?status=1') xhr.send(); xhr.open('POST','http://localhost/network/class7.../xx.php',true); xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); xhr.send('status=1&flag=1'); console.log(xhr.readState); xhr.onreadystatechange = function(){ console.log(xhr.readyState); if(xhr.readState === 4 && xhr.status === 200){ console.log(JSON.parse(xhr.responseText)); } }
$是什么,怎么定义 / 封装ajax
// test1 var $ = { ajax:function(opt){ var url = opt.url; console.log(url) }, post:function(){ console.log('post'); }, get:function(){ console.log('get'); }, xxx:function(){ ... } } // test2 $.ajax({ url:'http://www.baidu.com', type:'post' }) var $ = (function(){
var o = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP'); if(!o){ throw new Error('浏览器不支持ajax') } function _doAjax(opt){ var opt = opt || {}, type = (opt.type || 'GET').toUpperCase(), async = opt.async || true, url = opt.url, data = opt.data || null, error = opt.error || function(){}, success = opt.success || function(){}, complete = opt.ocmplete || function(){}; if(!url){ throw new Error('填写url'); } o.open(type,url,async); type === 'POST' && o.setRequestHeader('Content-type','application/x-www-form-urlencoded'); o.send(type === 'GET' ? null:formatDatas(data)); o.onreadystatechange= function(){ if(o.readyState === 4 && status === 200){ success(JSON.parse(o.responseText)); } if(o.status === 404){ error(); } complete(); } } function formatDatas(obj){ var str = ''; for(var key in obj){ str += key + '=' + obj[key] + '&'; } return str.replace(/&$/,''); } return { ajax:function(){ _doAjax(opt); }, post:function(){ }, get:function(){ } } })(); $.ajax({ type:'POST', url:'test.php', data:{ status:1, flag:2 }, success:function(data){ console.log(data); } }); $.post('test.php',{ status:1, flag:2 },function(data){ console.log(data) }) $.get('test.php?status=1',function(data){ console.log(data); });