初探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); });
复制代码

 

posted @   lisa2544  阅读(21)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示