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);
    }
  • 相关阅读:
    C#按模板生成word文档总结
    Aspose.Words.dll根据模板生成word
    WCF服务
    Fiddler抓包工具
    文本过长显示...
    java JDK 环境变量配置
    js return关键字
    js限制文本框输入内容
    jQuery学习一
    JSON 教程
  • 原文地址:https://www.cnblogs.com/mengff/p/6188042.html
Copyright © 2011-2022 走看看