﻿///种地的汉子 Created 2006

function HanZiAjax(options) {
    options = {
        timeout: options.timeout || 500,
        type: options.type || "post",
        url: options.url || "",
        onSuccess: options.onSuccess || function() { },
        onError: options.onError || function() { },
        onComplete: options.onCompete || function() { },
        data: options.data || ""
    };
    var xhr = new XMLHttpRequest();
    var requestDone = false;
    var timeoutLength = options.timeout;

    //Open
    xhr.open(options.type, options.url, true);

    //间隔请求
    setTimeout(function() { requestDone = true; }, timeoutLength);
    //响应的状态
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && !requestDone) {
            if (httpSuccess(xhr)) {
                options.onSuccess(httpData(xhr, options.type));
            }
            else {
                options.onError;
            }
            options.onComplete();
            xhr = null;
        }
    };

    //传递
    xhr.send(options.data);

    //取状态
    function httpSuccess(r) {
        try {
            return !r.status && location.protocol == "file:" || (r.status >= 200 && r.status <= 300) || r.status == 304
            || navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
        }
        catch (e) { }
        return false;
    }
    //取数
    function httpData(r, type) {
        var ct = r.getResponseHeader("content-type");
        var data = !type && ct && ct.indexOf("xml") >= 0;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        if (type == "script") eval(data);
        return data;
    }

}   
            
