从Ajax调用获得响应

时间:2013-07-29 23:53:26

标签: javascript ajax

当试图从普通的vanilla javascript构建的ajax调用中获取responseText时,Firebug似乎看到了请求但是无法获得对responseText的引用。

这是功能代码

function getAjaxResponse(){    
    var ajaxObj = getAjaxObj();
    ajaxObj.open('get', 'responsePage.php', true);
    ajaxObj.onReadyStateChanged = function(){
        if(ajaxObj.readyState == 4
            && ajaxObj.status == 200){
                //no functions are getting fired in here                
                //this does not get logged to console
                console.log(ajaxObj.responseText);
                //neither does this
                console.log(2);
        }
    };
    ajaxObj.send(null);

   //this does gets logged to console
   console.log(1);
}

ajax对象的函数

function getAjaxObj(){
    var req;  
    if(window.XMLHttpRequest){
        try{
            req = new XMLHttpRequest();                                                                 
        } catch(e){
            req = false;
        } finally {
            return req;
        }
    } else {
        if(window.ActiveXObject){
            try{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e){
                try{
                    req = new ActiveXObject("Msxml.XMLHTTP");
                } catch(e){
                    req = false;
                } finally {
                    return req;
            }
            }
        }
    }
}

这里也是萤火虫的观点 enter image description here

如何获取对ajax调用响应的引用?

2 个答案:

答案 0 :(得分:2)

OnReadyStateChanged需要onreadystatechange。 JavaScript区分大小写。

答案 1 :(得分:1)

ajaxObj.onReadyStateChangedonreadystatechange应该都是小写(并且没有尾随'd')