vulcan

          低頭做事,抬頭看路

             :: 首頁 :: 聯系 :: 聚合  :: 管理
            41 Posts :: 7 Stories :: 28 Comments :: 0 Trackbacks
            1/*Author: yican@cs-air.com
            2a simple ajax wrapper
            3*/

            4function Ajax() {
            5    var req = null;
            6    var postAction = null;//a hook
            7    var divName = "";
            8    /*post action hook definition*/
            9    this.setPostHook = function(f) {
           10        postAction = f;
           11    }

           12    //execute the remote method and refresh the page'd div
           13    this.sendRequest = function(url, div, method) {
           14        var callback = this.report;//default alert
           15        if(div != null){
           16            callback = this.processAjaxResponse;
           17            divName = div;
           18        }

           19        if(method == null{
           20            //method = "POST";//default POST - no character encoding problem
           21            method = "GET";//default GET
           22        }
           else {
           23            method = method.toUpperCase();
           24        }

           25        /*encode URL with Chinese*/
           26        url = encodeURI(url);
           27        //alert(url);
           28        //execute the remote method
           29        this.executeXhr(method, callback, url);
           30    }

           31    //this is call back method
           32    this.processAjaxResponse = function() {
           33        // only if req shows "loaded"
           34        var div = document.getElementById(divName);
           35        //display the process bar
           36        div.innerHTML = "loading";
           37        if (req.readyState == 4{
           38            // only if "OK"
           39            //alert(divName);
           40            //alert(div);
           41            if (req.status == 200{
           42            div.innerHTML = req.responseText;
           43            }
           else {
           44            alert("There was a problem retrieving the XML data:\n" +
           45            req.statusText);
           46            }

           47            //execute hook function
           48            if(postAction){
           49                postAction();
           50            }

           51        }

           52    }

           53    //alert
           54    this.report = function() {
           55        if (req.readyState == 4{
           56            // only if "OK"
           57            if (req.status == 200{
           58            alert(req.responseText);
           59            }
           else {
           60            alert("There was a problem retrieving the XML data:\n" +
           61            req.statusText);
           62            }

           63            //execute hook function
           64            if(postAction){
           65                postAction();
           66            }

           67        }

           68    }

           69    //execute ajax request
           70    this.executeXhr = function(method, callback, url) {
           71        // difine a XMLHttpRequest object
           72        if (window.XMLHttpRequest) {
           73            // branch for native XMLHttpRequest object
           74            req = new XMLHttpRequest();
           75        }
           else {
           76            // branch for IE/Windows ActiveX version
           77            req = new ActiveXObject("Microsoft.XMLHTTP");
           78        }

           79        try{
           80            req.setRequestHeader("Cache-Control: no-store, no-cache, must-revalidate");
           81            req.setRequestHeader("Connection","close");
           82        }
           catch(e){}
           83        //
           84        req.onreadystatechange = callback;
           85        if(method == "POST"{
           86            //split the url
           87            var urlWithParam = url.split("?");//split the url in two parts
           88            var urlPrefix = urlWithParam[0];//the url
           89            var arg = urlWithParam[1];//the arguments
           90            req.open("POST", urlPrefix, true);
           91            req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
           92            req.send(arg);
           93        }
           else {
           94            req.open("GET", url, true);
           95            //req.send(null);
           96            req.send();
           97        }

           98    }

           99}

          100//get all the form elements value
          101function getUrlForPost(form) {
          102    var url = "";
          103    url += (form.action + "?");//url start with the form's action
          104    var len = form.elements.length;
          105    for (i = 0; i < len; i++)
          106    {
          107        var e = form.elements[i];
          108        /*FIXME: can't get value of selectd options of multi select(a list)*/
          109        if(e.name != '') {//you can omit some value by set the element's name to blank
          110            if(e.type == 'checkbox' || e.type == 'radio') {
          111                //alert(e);
          112                //if it is a checked box
          113                if(e.checked) {
          114                    url += (e.name + "=");
          115                    url += (e.value + "&");
          116                }

          117            }
           else {
          118                url += (e.name + "=");
          119                url += (e.value + "&");
          120            }

          121        }

          122    }

          123    if(url.lastIndexOf('&') == (url.length - 1)) {
          124        //if the last char is a '&', get rid of it
          125        url = url.substring(0, url.length - 1);
          126    }

          127    //alert(url);//DEBUG
          128    return url;
          129}

          130/*A simple wrapper for submit a form*/
          131function submitForm(form, div, done, method) {
          132    var url = getUrlForPost(form);
          133    //alert(url);
          134    var object = new Ajax();
          135    if(done != null{
          136        object.setPostHook(done);
          137    }

          138    //post is the most common method for post a form
          139    if(method == null){
          140        method = "POST";//default 'POST'
          141    }

          142    //alert(method);
          143    object.sendRequest(url, div, method);
          144}

          使用方法:
          (1)提交請求,比如不刷新頁面的情況下在頁面制定DIV中顯示輸入表單或者其他內容:
          HTML:文件中定義<div id="result"></div>
          觸發函數:
          1var url = "http://somehost.com/do.action";
          2var object = new Ajax();
          3object.sendRequest(url,"result");
          4//默認為GET方法,如果在TOMCAT5中遇到亂碼問題可以選擇使用POST方法提交
          5//object.sendRequest(url,"result","POST");
          (2) 提交請求,如刪除某個項目之后刷新頁面或者重新讀取列表,操作提示用alert方法
          1var url = "http://somehost.com/do.action?id=ID";
          2var object = new Ajax();
          3//設定請求完成之后調用的函數
          4object.setPostHook(function(){window.location.reload();});
          5object.sendRequest(url);
          6
          (3)自動用Ajax方式提交表單
          在上面的js封裝中,有一個submitForm()方法,這個方法是為提交字段比較長的表單而特別設計的,它根據表單的各個屬性來自動生成URL,自動提交請求,它的效果與直接提交表單的效果差不多,具體使用參加代碼實現,不累述。
          posted on 2007-08-26 15:03 vulcan 閱讀(1320) 評論(1)  編輯  收藏 所屬分類: Web技術

          Feedback

          # re: [原創]一個簡單的Ajax封裝 2011-12-13 00:39 風動旛動
          發發生的  回復  更多評論
            


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 湖州市| 文山县| 秦皇岛市| 博白县| 凤翔县| 禹城市| 古交市| 安阳市| 新乡县| 淳化县| 丰宁| 东丽区| 斗六市| 宁晋县| 平泉县| 苏州市| 唐山市| 霍州市| 依安县| 边坝县| 河源市| 连江县| 巴彦淖尔市| 苗栗市| 绵竹市| 东乌珠穆沁旗| 漾濞| 祁阳县| 久治县| 黎平县| 大港区| 新化县| 咸阳市| 肇源县| 武陟县| 崇阳县| 大厂| 武川县| 廊坊市| 德安县| 吉水县|