首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ajax readyState总是返回0

Ajax readyState总是返回0
EN

Stack Overflow用户
提问于 2014-02-18 21:09:24
回答 1查看 1.3K关注 0票数 2

这个Ajax代码有问题,每次访问“readyState”时都返回0。不知道问题的根源是什么,任何帮助都是非常感谢的:

代码语言:javascript
复制
var xhr = null;
function performAjax(inputUrl){

    // instantiate XMLHttpRequest object
    try{
        xhr = new XMLHttpRequest();
        alert("XMLHttpRequest");
    }
    catch(e){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // handle old browsers
    if( xhr == null ) {
        alert("Ajax not supported by your browser");
        return;
    }

    // get the URL
    var url = inputUrl;
    alert(inputUrl);
    // get Ajax answer
    xhr.onreadystatechange = handler();
    //alert(xhr.readyState);
    xhr.open("POST", url, true);
    xhr.send(null);
}

function handler() {

    alert("Handler: " + xhr.readyState + " Status: " + xhr.status);
    // handle only loaded requests
    if(xhr.readyState == 4) {   // state 4: that data has been received
        alert("here");
        if(xhr.status == 200) { 
            alert(xhr.reponseText);
        }
        else alert("Error with Ajax");
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-18 21:13:29

您不正确地分配处理程序函数:

代码语言:javascript
复制
xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES

当您包含括号时,您要求调用该函数。没有它们,你仅仅是指函数,这就是你想要的。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21865375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档