+ -
当前位置:首页 → 问答吧 → 用 2 个函数实现 Ajax

用 2 个函数实现 Ajax

时间:2008-11-25

来源:互联网

Ajax 技术现在好多人懂了,但用的时候,代码五花八门,不易理解和维护。现在已经有一些 Ajax 框架,做的很不错,例如较早的 xAjax(PHP下的),还有现在的 jQuery、Dhtml 等。但因为框架要考虑通用性和兼容性等,实现起来叠床架屋的,比较复杂。对于我们一些小应用来说,用起来有大材小用、打炮大蚊子的感觉。
    其实 Ajax 被大家搞的神秘了 - 看看书店里那些千篇一律的、煞有介事的专门讲 Ajax 的书吧。
    以下代码把通过 get 方式实现 Ajax 请求的方法,构造成 2 个函数(不打算用类来实现),已经可以满足日常的简单应用,也几乎体现了 Ajax 的全部精髓。用的时候,给几个参数,调用函数就可以了。
    function getAjax(httpurl,requests,div)
    {
     if (typeof(httpurl,requests,div) == 'undefined')
     {
      return false;
     }
     var url = httpurl+requests;
     var show = document.getElementById(div);
     var ajax = InitAjax();
     ajax.open("GET", url, true);
     ajax.onreadystatechange = function() {
      if (ajax.readyState == 4 && ajax.status == 200) {
       show.innerHTML = ajax.responseText;
      }
     }
     ajax.send(null);
    }
    function InitAjax()
    {
     var ajax=false;
     try {
      ajax = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       ajax = false;
      }
     }
     if (!ajax && typeof XMLHttpRequest!='undefined') {
      ajax = new XMLHttpRequest();
     }
     return ajax;
    }
    张庆(网眼) 2008-11-25
    来自“网眼视界”:http://blog.why100000.com
    “十万个为什么”电脑学习网:http://www.why100000.com

作者: 西安PHPer   发布时间: 2008-11-25

嗯,简单

作者: andsky   发布时间: 2008-11-25

function createXMLHttpRequest() {
    var ua = null;
   
    if(window.XMLHttpRequest) {
                // ff & ie7
        try {
            ua = new XMLHttpRequest();
        } catch(e) {
                alert("Ajax not supported");
        };
    }
    else if(window.ActiveXObject) {
                // ie
            try {      
                    ua = new ActiveXObject("Microsoft.XMLHTTP");     
            } catch(e) {      
                alert("Ajax not supported");
            };   
    };   
    return ua;   
};
var loadAsync = function(uri, callback) {
        var xhr = createXMLHttpRequest();
        xhr.open("GET", uri, true);
        xhr.onreadystatechange = function() {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    callback(this.responseXML);
                };
        };
        };
        xhr.send(null);
};


在IE6下,if (this.readyState == 4) { 这个地方会报错。
IE7和Firefox都正常
不知道为什么。

作者: 0hudu   发布时间: 2008-11-25

这不是张老师麻.....

作者: looking   发布时间: 2009-02-21

如何用呢,有例子更好

作者: qai41   发布时间: 2009-02-21