Friday, October 8, 2010

Javascript prototype ajax and xml tools

it's menual code. work fine


tools.js file


///////////////////////////////////////////////////////////////////////////////
var WebTools = function() {
    var doc;

    this.constructor = null;

    this.valueOf = function(unknown) {
        return null;
    };

    this.toString = function(unknown) {
        return "";
    }

    this.toLocaleString = function(unknown) {
        return "";
    }

    this.setDocument = function(hdoc) {
        doc = hdoc;
    }

    this.getDocument = function() {
        return doc;
    }

    this.XmlTool = new function() {
        this.getXmlDocument = function(text) {
            var xmlDoc = null;
            try //Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(text);
            }
            catch (e) {
                try //Firefox, Mozilla, Opera, etc.
                {
                    parser = new DOMParser();
                    xmlDoc = parser.parseFromString(text, "text/xml");
                }
                catch (e) {
                    return null;
                }
            }
            return xmlDoc;
        };

        this.getXMLString = function(xmlDoc) {
            var serialized;
            try {
                // XMLSerializer exists in current Mozilla browsers
                serializer = new XMLSerializer();
                serialized = serializer.serializeToString(xmlDoc);
            }
            catch (e) {
                // Internet Explorer has a different approach to serializing XML
                serialized = xmlDoc.xml;
            }
            return serialized;
        };

        this.createXmlDocument = function() {
            var xmlDoc = null;
            // code for IE   
            if (window.ActiveXObject) {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
            }
            // code for Mozilla, Firefox, Opera, etc.
            else if (document.implementation.createDocument) {
                xmlDoc = document.implementation.createDocument("", "", null);
            }
            return xmlDoc;
        };

        this.openXmlDocument = function(xmlFile) {
            if (window.ActiveXObject) { //Internet Explorer
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            } else if (document.implementation && document.implementation.createDocument) {
                xmlDoc = document.implementation.createDocument("", "", null);
            }
            try {
                xmlDoc.async = false;
                xmlDoc.load(xmlFile);
            }
            catch (e) { alert(e.message); }
        };
    };

    this.Converter = new function() {
        this.Win1251ToUtf8 = function(str) {
            var strlen = str.length;
            var utf8_str = "";

            for (i = 0; i < strlen; i++) {
                var codestr = str.charCodeAt(i);
                switch (codestr) {
                    case 184: codestr = 1105; break; //eo
                    case 168: codestr = 1025; break; // capital EO

                    case 175: codestr = 1198; break; //capital UE
                    case 191: codestr = 1199; break; //ue

                    case 170: codestr = 1256; break; // capital OE
                    case 186: codestr = 1257; break; //oe
                }
                if (256 > codestr && codestr > 191) codestr = codestr + 848;
                switch (codestr) {
                    case 1111: codestr = 1199; break;   //u
                    case 1031: codestr = 1198; break; //capital U

                    case 1108: codestr = 1257; break; //ou
                    case 1028: codestr = 1256; break; //capital OU
                }

                utf8_str = utf8_str + String.fromCharCode(codestr);
            }
            return utf8_str;
        };
    };

    this.Sender = new function() {
        var postFrameIndex = 0;
        this.getPostID = function(nam) {
            postFrameIndex++;
            return (nam + postFrameIndex);
        };

        this.dynamicPostSend = function(formid, hfunc) {
            var postid = this.getPostID("post");
            iframeId = document.createElement("FRAME");
            iframeId.src = "";
            iframeId.id = postid;
            iframeId.name = postid;
            callBackEvent = function(fra, func) {
                if (fra.contentDocument) {
                    content = fra.contentDocument.body.innerHTML;
                } else if (fra.contentWindow) {
                    content = fra.contentWindow.document.body.innerHTML;
                } else if (fra.document) {
                    content = fra.document.body.innerHTML;
                }
                if (content != null && content != "")
                    func(fra, content);
                try {
                    //fra.parentNode.removeChild(fra);
                } catch (e) {
                }
            };
            document.body.appendChild(iframeId);
            iframe = document.getElementById(postid);
            callBack = function() {
                callBackEvent(iframe, hfunc);
                /*
                if (iframeId.document != null && iframeId.document + "" != "undefined") {
                iframeId.onreadystatechange = function() {
                if (iframeId.readyState + "" == "complete") {
                callBackEvent(iframeId, hfunc);
                }
                };
                } else {
                iframeId.onload = function() {
                callBackEvent(iframeId, hfunc);
                };
                }*/
            };
            iframe.onload = callBack;
            hform = document.getElementById(formid);
            hform.target = postid;
            /*
            var str = "<iframe id='" + postid + "' name='" + postid
            + "' src='' onload='callBack(this)' style='display:none; height:0px; width:0xp;'></iframe>";
            var formid = "";
            if (typeof (form) + "" == "string")
            formid = form;
            else
            formid = form.id;
            hform = document.getElementById(formid);
            parNode = hform.parentNode;
            var innert = parNode.innerHTML;
            parNode.innerHTML = innert + str;
            hform = document.getElementById(formid);
            */
            //form.setAttribute("enctype", "application/x-www-form-urlencoded");
            //form.setAttribute("encoding", "multipart/form-data");           
            hform.submit();
        };
    };

    this.AjaxTool = new function() {
        this.createAjaxRequest = function() {
            var http_request;
            if (window.XMLHttpRequest) {
                http_request = new XMLHttpRequest();
                //if (http_request.overrideMimeType) {
                //    http_request.overrideMimeType("text/xml");
                //http_request.overrideMimeType("text/html");
                //}
            } else {
                var msxmlhttp = new Array("Msxml2.XMLHTTP.4.0",
                "Msxml2.XMLHTTP.3.0",
                "Msxml2.XMLHTTP",
                "Microsoft.XMLHTTP");
                for (var i = 0; i < msxmlhttp.length; i++) {
                    try {
                        http_request = new ActiveXObject(msxmlhttp[i]);
                        if (http_request != null) return http_request;
                    } catch (e) {
                        http_request = null;
                    }
                }
            }
            return http_request;
        };

        this.quickSet = function(url, hfunc) {
            var xmlHttp = null;
            xmlHttp = this.createAjaxRequest();
            if (xmlHttp != null) {
                xmlHttp.open("get", url, true);
                xmlHttp.onreadystatechange = function() {
                    try {
                        if (xmlHttp.readyState == 4) {
                            //Request OK
                            if (xmlHttp.status == 200) {
                                hfunc(xmlHttp);
                            }
                        }
                    } catch (e) {
                        alert("XmlHTTP-д ажиллахад асуудал гарлаа!");
                    }
                }
                xmlHttp.send(null);
            } else {
                alert("Таны веб хөтөч XmlHTTP-г дэмжихгүй байна!");
            }
        };

        this.quickGet = function(url, args, hfunc) {
            var xmlHttp = null;
            xmlHttp = createAjaxRequest();
            if (xmlHttp != null) {
                xmlHttp.open("get", url + args, true);
                xmlHttp.setrequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xmlHttp.onreadystatechange = function() {
                    try {
                        if (xmlHttp.readyState == 4) {
                            //Request OK
                            if (xmlHttp.status == 200) {
                                hfunc(xmlHttp);
                            }
                        }
                    } catch (e) {
                        alert("XmlHTTP-д ажиллахад асуудал гарлаа!");
                    }
                }
                xmlHttp.send(null);
            } else {
                alert("Таны веб хөтөч XmlHTTP-г дэмжихгүй байна!");
            }
        };

        this.AjaxMessage = function(msg) {
            alert(msg);
        };

        this.postSend = function(url, parameters, hfunc) {
            http_request = this.createAjaxRequest();
            if (http_request != null) {
                http_request.open("POST", url, true);
                //http_request.setRequestHeader("Content-Type", "text/xml");
                http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                //http_request.setRequestHeader("Content-Length", parameters.length);
                //http_request.setRequestHeader("Connection", "close");
                http_request.onreadystatechange = function() {
                    if (http_request.readyState == 4) {
                        if (http_request.status == 200) {
                            result = http_request.responseText;
                            hfunc(result);
                        } else {
                            alert("XmlHTTP-д ажиллахад асуудал гарлаа!");
                        }
                    }
                }
                http_request.send(parameters);
            } else hfunc("error");
        };

        this.encodeInput = function(form) {
            inputs = form.getElementsByTagName("input");
            var retParams = "";
            for (var i = 0; i < inputs.length; i++) {
                inputNode = inputs[i];
                var inputName = inputNode.name;
                var inputvalue = inputNode.value;
                retParams = retParams + inputName + "=" + ((inputvalue != null) ? inputvalue : "");
                if ((i + 1) < inputs.length)
                    retParams = retParams + "&";
            }
            return retParams;
        };

        this.postParameters = function(obj) {
            var getstr = "";
            for (i = 0; i < obj.getElementsByTagName("input").length; i++) {
                if (obj.getElementsByTagName("input")[i].type == "text") {
                    getstr += obj.getElementsByTagName("input")[i].name + "=" +
                   obj.getElementsByTagName("input")[i].value + "&";
                }
                if (obj.getElementsByTagName("input")[i].type == "checkbox") {
                    if (obj.getElementsByTagName("input")[i].checked) {
                        getstr += obj.getElementsByTagName("input")[i].name + "=" +
                   obj.getElementsByTagName("input")[i].value + "&";
                    } else {
                        getstr += obj.getElementsByTagName("input")[i].name + "=&";
                    }
                }
                if (obj.getElementsByTagName("input")[i].type == "radio") {
                    if (obj.getElementsByTagName("input")[i].checked) {
                        getstr += obj.getElementsByTagName("input")[i].name + "=" +
                   obj.getElementsByTagName("input")[i].value + "&";
                    }
                }
                if (obj.getElementsByTagName("input")[i].tagName == "SELECT") {
                    var sel = obj.getElementsByTagName("input")[i];
                    getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
                }
            }
            return getstr;
        };

        this.getParameters = function(obj) {
            var getstr = "?";
            for (i = 0; i < obj.childNodes.length; i++) {
                if (obj.childNodes[i].tagName == "INPUT") {
                    if (obj.childNodes[i].type == "text") {
                        getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
                    }
                    if (obj.childNodes[i].type == "checkbox") {
                        if (obj.childNodes[i].checked) {
                            getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
                        } else {
                            getstr += obj.childNodes[i].name + "=&";
                        }
                    }
                    if (obj.childNodes[i].type == "radio") {
                        if (obj.childNodes[i].checked) {
                            getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
                        }
                    }
                }
                if (obj.childNodes[i].tagName == "SELECT") {
                    var sel = obj.childNodes[i];
                    getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
                }
            }
            return getstr;
        }
    };
};

var webTools = new WebTools();

USAGE:

simple.js file ( book search on js of asp.net )

var oldSearchType;

function SelectSearchType(stype) {   
    if (oldSearchType == null)
        oldSearchType = document.getElementById("SearchType_Title");
    if (oldSearchType != null) {
        if(stype != null)
            oldSearchType.className = "";
    }
    if (stype != null) {
        stype.className = "SelectedSearchType";
        oldSearchType = stype;
    }
}

function ToogleNextSearch() {
    snext = document.getElementById("NextSearchCheck");
    if (snext.checked)
        snext.checked = false;
    else
        snext.checked = true;
}

function SearchBook() {
    SearchBookNext();
    return false;
}

function SearchBookNext() {   
    SelectSearchType(null);
    var searchTypeid = oldSearchType.id;
    var ind = searchTypeid.indexOf('_');
    document.getElementById("ctlSearchType").value = searchTypeid.substring(ind + 1);   
    document.getElementById("ctlPageStart").value = 0;
    document.getElementById("ctlPageLen").value = 10;
    snext = document.getElementById("NextSearchCheck");
    document.getElementById("ctlNextSearch").value = ((snext.checked) ? "1" : "0");   
    form = document.getElementById("frmSearchBook");   
    var params = webTools.AjaxTool.encodeInput(form);

    retfunc = function(content) {
        try {           
            xml = webTools.XmlTool.getXmlDocument(content);
            //alert(xml.firstChild.nodeName);
            //alert(webTools.XmlTool.getXMLString(xml));
            var root = xml.firstChild;
            if (root != null && root.childNodes.length > 0) {               
                //alert(root.getElementsByTagName("info").length);
                //alert(root.getElementsByTagName("book").length);
                var vars = root.getElementsByTagName("info")[0];
                var rlength = parseInt(vars.childNodes[0].firstChild.nodeValue);
                var rstart = parseInt(vars.childNodes[1].firstChild.nodeValue);
                var rlimit = parseInt(vars.childNodes[2].firstChild.nodeValue);
                if (rlength < rstart && rlength < rlimit) rlimit = Math.abs(rlength - rlimit);
                var books = root.getElementsByTagName("book");
                if (books.length > 0) {
                    var alll = "<li><div>Хайлтын үр дүн: <span>(" + rlength + " -c " + (rstart + rlimit) + ")</span></div></li>";
                    for (var i = 0; i < books.length; i++) {
                        var book = books[i].childNodes;
                        var BookTitle = ((book[0].firstChild != null) ? book[0].firstChild.nodeValue : "");
                        var Author = ((book[1].firstChild != null) ? book[1].firstChild.nodeValue : "");
                        var Synopsis = ((book[2].firstChild != null) ? "<b>Агуулга: </b>" + book[2].firstChild.nodeValue : "");
                        var Keywords = ((book[3].firstChild != null) ? " << " + book[3].firstChild.nodeValue : "");
                        var Typename = ((book[4].firstChild != null) ? book[4].firstChild.nodeValue : "");
                        var Genres = ((book[5].firstChild != null) ? book[5].firstChild.nodeValue : "");
                        var Publisher = ((book[6].firstChild != null) ? book[6].firstChild.nodeValue : "");
                        var Bookid = ((book[7].firstChild != null) ? book[7].firstChild.nodeValue : "");

                        var ihtml = "<li><div><A href='javascript:void(0);' onclick='javascriopt:SelectBookInfo();' id='" + Bookid + "'>"
+ BookTitle + "</A> <A>- " + Author + "</A></div><div><p>" + Synopsis + "<span>"
+ Keywords + "</span></p></div><div><font><B>Төрөл:</B> " + Typename + " <B>, Жанар:</B> "
+ Genres + " </font></div><div><pre>" + Publisher + "</pre></div></li>";

                        alll = alll + ihtml;
                    }
                    document.getElementById("SearchResultUL").innerHTML = alll;
                }
            }
            else {
                alert("Search Failed: " + book);
            }
        } catch (e) {
            document.getElementById("SearchResultUL").innerHTML = "<li>Алдаа илэрсэн. Та дахин хайна уу!</li><li>" + e + "</li>";
        }
    };
    try {
        webTools.AjaxTool.postSend("../cinc/cserve.aspx", params, retfunc);
    } catch (e) { }   
}

function CallAccountSetting() {
    alert("callAccountSetting()");
}

function LoadSearchBody() {
}

No comments: