Ajax entry (ii) a function package Ajax

Transfer from my personal blog site
if I read on a blog, " Ajax Starter (a) from zero to a successful GET request ," then certainly we know that we have completed a simple request to get the function. as follows:

/**
 * 一个简单的get请求
 * @param {String}   url     请求地址,文件名
 * @param {Function} fnSucc  请求成功时执行的函数
 * @param {Function} fnFaild 请求失败执行的函数
 */
function AJAX(url, fnSucc, fnFaild) {
    //1.创建ajax对象
    var oAjax = null;
        /**
         * 此处必须需要使用window.的方式,表示为window对象的一个属性.不存在时值为undefined.
         * 进入else若直接使用XMLHttpRequest在不支持的情况下会报错
         **/
    if (window.XMLHttpRequest) {
        //IE6以上
        oAjax = new XMLHttpRequest();
    } else {
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2.连接服务器
    //open(方法,url,是否异步)
    oAjax.open("GET", url, true);

    //3.发送请求
    oAjax.send();

    //4.接收返回
    //OnRedayStateChange事件
    oAjax.onreadystatechange = function () {
        if (oAjax.readyState === 4) {
            if (oAjax.status === 200) {
                //                alert("成功" + oAjax.responseText);
                fnSucc(oAjax.responseText);
            } else {
                //                alert("服务器响应失败!");
                if (fnFaild) {
                    fnFaild();
                }
            }
        }
    };
}

Why continue with Ajax function package?
For the following reasons:

  1. Current methods use only get requests, but can not use the post request, you must use POST when a user registration, because POST, now incomplete.

  2. At present the request parameters can only be written directly in the url, is not conducive to dynamic access to data, parameters should be used to resolve the way, easy to use.

  3. get request method request caching issues.

  4. Learning encapsulation method,

Transformation goals

function ajax(url, options) {
    // your implement
}

options is an object, which may include the parameters:

  • type: post or get, you can have a default value

  • data: data transmitted, as a key object or to a connection with the string & Assignment

  • onsuccess: When calling a function of success

  • onfail: call the function for failure

Transformation start (three steps)

Transformation (a) of the original function

Parameter, delete fnSucc, fnFaildadd options. That the success and failure functions performed becomes options object onsuccess, onfailtwo methods corresponding value.
Mainly in 4, receiving the return portion is changed as follows

//4.接收返回
oAjax.onreadystatechange = function () {
    if (oAjax.readyState === 4) {
        if (oAjax.status === 200) {
            //请求成功。形参为获取到的字符串形式的响应数据
            options.onsuccess(oAjax.responseText);
        } else {
            //先判断是否存在请求失败函数
            //存在时,形参为XMLHttpRequest对象,便于进行错误进行处理
            if (options.onfail) {
                options.onfail(oAjax);
            }
        }
    }
};

(B) processing the request parameter

First of all we want to know is when there is a request to use parameters, request parameters GET method is particularly simple. Directly behind the url add? Parameter name = value & parameter parameter name = parameter value of two two

Realization of ideas:

  1. First, determine whether there is options.data used when there is no "?timestamp= + new Date().getTime();link in the url, in order to clear the cache.

    • Here is the method I use, timestamp herein may be altered

    • new Date().getTime();It can also be used Math.random();mainly to keep the url each request is different.

    • There are many other ways to reference how Ajax cache solve the problem? . Interested themselves more google it.

  2. Options.data presence, should facilitate the handling restriction request data format is set to JSON (of course not necessarily so strict as JSON, it should be kept in the form key).

  3. Data used for in traversal using =to connect with the key values, used &to connect a plurality of request parameters

  4. Only the original function of 2. Connect server change

To achieve the following:

original:

//2.连接服务器
//open(方法,url,是否异步)
oAjax.open("GET", url, true);

Now:

//open(方法,url,是否异步)
var param = "";//请求参数。
//判断data存在时缓存它,不存在时,设为0
var data = options.data ? options.data : 0;
if(typeof(data)==="object"){//只有data为对象使才执行
    for (var key in data){//请求参数拼接
        if (data.hasOwnProperty(key)) {
            param += key+"="+data[key]+"&";
        }
    }
    param.replace(/&$/,"");//去除结尾的&。
}else{
    param= "timestamp=" + new Date().getTime();
}
//2.连接服务器
oAjax.open("GET", url+"?"+param, true);

(C) selection request type

With the post sending data, the analog form submission. In the url can not see the request parameters, more secure.

Realization of ideas:

  1. Whether the type to determine whether there is, converted to uppercase when present, the default is the GET request.

  2. Determining the type of request, GET, or POST.

  3. When using the post request to submit data, request parameter is not followed url.

  4. With the post must be added in the request data open()with the send()direct addition of header information.

    • xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  5. With the post request data, 2. Connect server 3 transmits a request section for processing

To achieve the following:

original:

//2.连接服务器
oAjax.open("GET", url+"?"+param, true);

Now :

//3.发送请求
var type = options.type ? options.type.toUpperCase() : "GET" ;
if(type ==="GET"){
    oAjax.open("GET", url+"?"+param, true);
    oAjax.send();
}else{
    oAjax.open("POST", url, true);
    oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    oAjax.send(param);
}

Final completion

Written before the combination group together.

/**
 * AJAX函数封装
 * @param {string} url     请求地址(必须)
 * @param {object} options 发送请求的选项参数
 *   @config {string} [options.type] 请求发送的类型。默认为GET。
 *   @config {Object} [options.data] 需要发送的数据。
 *   @config {Function} [options.onsuccess] 请求成功时触发,function(oAjax.responseText, oAjax)。(必须)
 *   @config {Function} [options.onfail] 请求失败时触发,function(oAjax)。(oAJax为XMLHttpRequest对象)
 *
 *@returns {XMLHttpRequest} 发送请求的XMLHttpRequest对象
 */
function AJAX(url, options) {
    //1.创建ajax对象
    var oAjax = null;
        /**
         * 此处必须需要使用window.的方式,表示为window对象的一个属性.不存在时值为undefined,进入else
         * 若直接使用XMLHttpRequest,在不支持的情况下会报错
         **/
    if (window.XMLHttpRequest) {
        //IE6以上
        oAjax = new XMLHttpRequest();
    } else {
        oAjax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    //2.连接服务器
    //open(方法,url,是否异步)
    var param = ""; //请求参数。
    //只有data存在,且为对象使才执行
    var data = options.data ? options.data : -1; //缓存data
    if (typeof (data) === "object") {
        for (var key in data) { //请求参数拼接
            if (data.hasOwnProperty(key)) {
                param += key + "=" + data[key] + "&";
            }
        }
        param.replace(/&$/, "");
    } else {
        param = "timestamp=" + new Date().getTime();
    }

    //3.发送请求
    var type = options.type ? options.type.toUpperCase() : "GET";
    if (type === "GET") {
        oAjax.open("GET", url + "?" + param, true);
        oAjax.send();
    } else {
        oAjax.open("POST", url, true);
        oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        oAjax.send(param);
    }

    //4.接收返回
    //OnRedayStateChange事件
    oAjax.onreadystatechange = function () {
        if (oAjax.readyState === 4) {
            if (oAjax.status === 200) {
                //请求成功。形参为获取到的字符串形式的响应数据
                options.onsuccess(oAjax.responseText, oAjax);
            } else {
                //先判断是否存在请求失败函数
                //存在时,形参为XMLHttpRequest对象,便于进行错误进行处理
                if (options.onfail) {
                    options.onfail(oAjax);
                }
            }
        }
    };
    return oAjax;//发送请求的XMLHttpRequest对象
}

Final completion is the case. Of course, far from perfect, such as try catchthe use, but by such a package, or learn a lot.

Guess you like

Origin www.cnblogs.com/homehtml/p/12661863.html