简体   繁体   English

XMLHttpRequest,状态为0

[英]XMLHttpRequest with status 0

I'm trying to use XMLHttpRequest, but when I call xmlhttp.send(post), I received xmlhttp with state 1 and status 0. I think that state equals 1 is ok, because mean server connection established, but why status 0? 我正在尝试使用XMLHttpRequest,但是当我调用xmlhttp.send(post)时,我收到状态为1且状态为0的xmlhttp。我认为状态等于1是正常的,因为建立了意味着服务器连接,但为什么状态为0? Unfortunately, the other side doesn't receive my request. 不幸的是,对方没有收到我的请求。

function ajaxRequest(method, url, post, callback_fn){
    var xmlhttp;
    if (window.XMLHttpRequest) { //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { //code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open(method,url,true);
    if (method=="POST"){
        xmlhttp.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        xmlhttp.setRequestHeader("Content-Length", post.length);
    }
    xmlhttp.send(post);
    console.log("xmlhttp.readyState = " + xmlhttp.readyState); // = 1
    console.log("xmlhttp.status = " + xmlhttp.status); // = 0
}

Can someone help me? 有人能帮我吗?

The onreadystatechange event fires when the state changes, and only when there's a return response can you check what the statusCode of the request was (200, 404 etc.) onreadystatechange事件在状态发生变化时触发,只有在有返回响应时才能检查请求的statusCode是什么(200,404等)

function ajaxRequest(method, url, post, callback_fn){
    var xmlhttp;
    if (window.XMLHttpRequest) { //code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { //code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            console.log("xmlhttp.status = " + xmlhttp.status);
        }
    }

    xmlhttp.open(method,url,true);
    if (method=="POST"){
        xmlhttp.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        xmlhttp.setRequestHeader("Content-Length", post.length);
    }
    xmlhttp.send(post);
}

Cancel the click and see if it stops the status zero. 取消单击,查看是否停止状态为零。

onclick="ajaxRequest(...); return false;"

Problem is page is refreshing and killing the Ajax request. 问题是页面刷新并查杀Ajax请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM