你十八了吗

10.19随笔

Ajax(阿贾克斯)
优点: 实现局部刷新(异步方式-页面继续操作,无需等待,无刷新)
缺点: 跨域(违背了同源策略)[Proxy代理,JSONP,CORS]
同源策略:
要访问的地址:协议名相同,域名相同,端口相同

 

同步与异步
同步:打电话(等待,阻塞)
        var w=show();
        console.log(w);//123
异步:发信息(非阻塞)
        show(function(w){
            console.log(w);//123
        })
        .........下面的代码继续执行...................
 
 
 
 
 

 

 

 

 

 

补充

JSON.parse();  字符串转成对象

 
 
 
Ajsx.js代码
/**
*Ajax请求
* @param{String} url 请求地址
* @param{String} method 请求方式(GET/POST)
* @param{Object} data 请求数据(POST)
* @param{Function} success 成功的回调函数
* @param{Function} fail 失败的回调函数
*/

function ajax(url,method,data,success,fail){
    //1.生成异步对象
    var xhr;
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();//主流浏览器
    }else{
        xhr=new AcitiveXObject('Microsoft.XMLHTTP');//老IE
    }
    //2.创建连接(打开通道)
    xhr.open(method,url,true);
    //3.发送
    xhr.send(data);
    //4.监听事件,获取结果
    xhr.onreadystatechange=function(){
        //readyState:发送状态,4表示发送完毕
        if(this.readyState===4){
            //status:返回的结果,200表示成功
            if(this.status==200){
                //调用success回调函数
                success(this.responseText);//responseText:结果
            }else{
                //调用fail回调函数
                fail(this.status);//将失败的状态码传递进去
            }
        }
    }
}

posted on 2018-10-22 21:02  你十八了吗  阅读(93)  评论(0编辑  收藏  举报

导航