zoukankan      html  css  js  c++  java
  • 结合prototype和xmlhttprequest封装ajax请求

    由于拖延症的严重以及年前准备年会(借口*^__^*)
    导致这个小的的思考  现在才算完成
    再怎么说也算是上班以来带我的前辈第一次这么正式的给我出题
    不管是出于尊重还是自我要求我都决定把它简要的记下来
    ......
     
    1.了解prototype
           原型对象的作用,就是定义所有实例对象共享的属性和方法。具体理解见实际操作中
     
    2.给String Date等对象增加继承方法
      要求结果:比如var date = "2016-01-01 00:00:00";date.format();要求输出"2016-01-01";
    eg:
    String.prototype.format = function(){
        return this.substring(0,10);
    };
    var str1 = "2016-01-01 00:00:00";
    alert(str1.format(str1));
     
     
    3.了解xmlhttprequest,能发送及接受ajax,以及分析response对象
             
      response属性为只读,返回接收到的数据体(即body部分),他的类型可以是ArrayBuffer、Blob、Document、JSON对象、或者一个字符串。由XMLHttpRequest.responseType属性的值决定。
     
    4.结合xmlhttprequest+prototype 自己封装一个请求
     
    本以为信手拈来,就这样的随便的敷衍写了一下,发现各种对原生的ajax不熟悉
    于是仔细的看了一下原生的ajax相关的各个属性,复习了下相关用法
    同时也参照了一些网络博客综合一下,对ajax进行了简单的封装
    XMLHttpRequest.prototype.ajax = function(type,url,data,success,error){
        var _this = this;
        if(typeof data == 'object'){
            var tempStr = '';
            for(var key in data){
                tempStr += key + '=' + data[key] + '&';
            }
            data = tempStr.replace(/&$/,'');
        }
        if(type = 'GET'){
            if(data){
                this.open('GET',url + '?' + data, true);
            }else{
                this.open('GET',url + '?version=' + Math.random(),true);
            }
            this.send();
        }else if(type == 'POST'){
            this.open('POST',url,true);
            this.setRequestHeader("content-type","application/x-www-form-urlencoded");
            this.send(data);
        }
        this.onreadystatechange = function () {
            if(this.readyState == 4){
                if(this.status == 200){
                    success(this.responseText);
                }else{
                    if(error){
                        error(this.status);
                    }
                }
            }
        }
    };
    
    //ajax test
    var xhr = new XMLHttpRequest();
    xhr.ajax('GET','https://secure.ec.qa.sunyuki.com/v0/items/11111',null,function(data){
        alert(data);
    });
     
     
  • 相关阅读:
    python基础(三)python数据类型
    python基础(二)条件判断、循环、格式化输出
    postman测试上传文件
    postman添加权限验证
    postman添加cookie
    postman发送json格式的post请求
    postman发送post请求
    如果json中的key需要首字母大写怎么解决?
    fastjson转jackson
    git初识
  • 原文地址:https://www.cnblogs.com/guoshan/p/6515839.html
Copyright © 2011-2022 走看看