zoukankan      html  css  js  c++  java
  • ajax方法简单实现

    ajax基本步骤

    1. 判断方法类型,GET,POST或其他

    2. 得到数据,&分隔的key value字符串形式

    3. 注册onreadystatechange事件

    4. 开启请求,调用open

    5. 发送数据,调用send

    ajax的过程状态

    xhr.readystate
    0 未初始化
    1 请求开启,但未发送,open后send前
    2 请求已发送,send后
    3 响应头已接收,响应体未完成
    4 响应全部接收
    function ajax(options){
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('...');
        var {url,method,data,async,success,fail} = options;
        var sendBody = null;
        var qs = Object.keys(data).reduce(function(cur,pre,index){
            return pre + '&' + encodeURIComponent(cur) + '=' + encodeURIComponent(data[cur]);
        },'').slice(1);
        if(medthod == 'get'){
            url += '?' + qs;
        }
        else if(medhot == 'post'){
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            sendBody = qs || null;
        }
        xhr.onreadystatechange = function(){
            if(xhr.readystate == 4){
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                    success && success(xhr.responseText);
                }
            }
            else{
                fail && fail({
                    status:xhr.status,
                    statusText:xhr.statusText
                });
            }
        }
        xhr.open(method,url,async);
        xhr.send(sendBody);
    }
  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/mengff/p/6188042.html
Copyright © 2011-2022 走看看