JavaScript之Ajax Util

  
  ajax(即:Asynchronous JavaScript and XML(异步的 JavaScript 和 XML))经常在用,却经常忽略了底层的实现机制,今日写个小工具,大家也可拿去使用,如果写博客时需要引用时,请显著地注明出处,以尊重劳动成果,谢谢~

  声明:本文仅讲述关于:JavaScript的ajax工具类设计ajax规范设计者开放了哪些接口、以及ajax使用Demo

 

零、推荐文献

  [1] 轻量级AJAX库-搜狗实验室ajax.js 

  [2] 跨域问题小结

一、Chrome控制台网络调试小工具[方便、快捷、易用]

 

var xml = new XMLHttpRequest();
xml.withCredentials = true; // 开启Cookie,启用会话机制
var url = "http://10.66.1.1/abc.jsp";      
xml.open('POST', url, true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score=5&abc=6");

 

  But,注意一个问题:不同的ajax请求对象,如何保持会话Session/Cookie的问题 

   如果ajax对象不主动设置xml.withCredentials=true(携带Cookie),则Chrome控制台每new XMLHttpRequest()一次ajax请求对象,就是新建一次会话

 

二、Ajax Util工具类设计

  文末处,附属个人的一些笔记的截图(确实值得一阅)。如有不妥之处,还请大家指正,共同进步~

/**
 * Ajax Util
 * 
 * @Author    JohnnyZen
 * @DateTime  2017-11-22
 * @copyright [johnny.weily]
 * @license   [license]
 * @version   [version]
 * @link      http://www.johnnyzen.cn/
 * @required  itemX
 * 
 * @param     option { url[,method][,data][,async][,dataType]}
 * 
 * @method    设置option,初始化ajax
 * @method    complete:请求完成时运行的函数(在请求成功或失败之后均调用,即在success和error函数之后)
 *                        complete:function(responseText,status,event){}    
 *                        complete:function(xhr,status){}    
 * @method    success:当请求成功时运行的函数
 *                        success:function(responseText,status,event){}
 *                        success:function(response,status,xhr){}
 * @method    error:请求出错时候的函数    
 *                        error:function(xhr,status,error){}
 *                        
 * @notice    xhr        用于创建 XMLHttpRequest 对象的函数
 * @notice    event.target.readyState的各值意义
 *             
                XMLHttpRequest.DONE                            4 响应完成或已失败 
                XMLHttpRequest.LOADING                         3 已收到服务器响应
                XMLHttpRequest.HEADERS_RECEIVED                2 已收到服务器响应的标头
                XMLHttpRequest.OPEND                           1 已调用open方法
                XMLHttpRequest.UNSENT                          0 已创建XMLHttpRequest对象   
 */

var Ajax = function(option){
    this.option = {
        url: null,
        type: option.type == undefined ? "GET" : option.type,
        async: option.async == undefined ? true : option.async,
        data: option.data == undefined ? null : option.data,
        contentType: option.contentType == undefined ? option.contentType : "application/x-www-form-urlencoded; charset=UTF-8",
        complete: typeof(option.complete) == 'function' ? option.complete : this.defaultCompleteHandle,
        success: typeof(option.success) == 'function' ? option.success : this.defaultSuccessHandle,
        error:typeof(option.error) == 'function' ? option.error : this.defaultErrorHandle
    },
    this.createAjaxRequest = function(){
        var AjaxRequest = null;// 缓存XHR对象便于 Ajax 使用
        try {
            // Opera 8.0+, Firefox, Safari
            AjaxRequest = new XMLHttpRequest();
        } catch (e) {
 
            // Internet Explorer Browsers
            try {
                AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // 错误处理
                    throw new Error("Your browser broke!");
                    return false;
                }
            }
        }
        return AjaxRequest;
    },
    this.defaultCompleteHandle = function(responseText,status,event){
            console.log("[Ajax#defaultCompleteHandle] responseText:", event.target.responseText); //test
            console.log("[Ajax#defaultCompleteHandle] status:", event.target.status); //test
    },
    this.defaultSuccessHandle = function(responseText,status,event){
             console.log("[Ajax#defaultSuccessHandle] responseText:", event.target.responseText); //test
             console.log("[Ajax#defaultSuccessHandle] status:", event.target.status); //test
    },
    this.defaultErrorHandle = function(event){
        console.error("defaultErrorHandle:", "ajax request failed!");
    },
    (function(){
        var AjaxRoot = this;//保存当前调用的根对象
        var AjaxRequest = AjaxRoot.createAjaxRequest();
        try{
            AjaxRequest.onreadystatechange = function(event){
     //         console.log("option.log:",AjaxRoot.option.log);//test

                if( event.target.readyState == XMLHttpRequest.DONE){// 4 响应完成或已失败  
                    console.log('AjaxRoot.option.complete', AjaxRoot.option.complete);    
                    AjaxRoot.option.complete(event.target.responseText,event.target.status,event);
                } else if(event.target.readyState == XMLHttpRequest.LOADING){// 3 已收到服务器响应
                    AjaxRoot.option.success(event.target.responseText,event.target.status,event);
                }
            }
            AjaxRequest.open(AjaxRoot.option.type, AjaxRoot.option.url, AjaxRoot.option.async);
            //ajax.open(option.method,option.url,[是否异步请求,默认为true:true],[user],[password]);
            
            console.log('AjaxRoot.option.data',AjaxRoot.option.data);//test
            AjaxRequest.send(AjaxRoot.option.data); 
        }catch(e){
            console.error(e);
            AjaxRoot.option.error();
            return false;
        }
    })();
}







//Ajax Util demo 
var option = {
    type:"GET",
    url:"http://apis.baidu.com/beijingprismcubetechnology/qmpapi/qmpproduct",
    async:true,//是否异步
    dataType:"json",
    data:"hello",
    complete:function(responseText,status,event){
        console.log("complete:",responseText);
    }
}

Ajax(option);

 

三、Ajax规范设计者们所提供的接口和一些常见问题的解决方案

 

转载于:https://www.cnblogs.com/johnnyzen/p/7880657.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值