douxin1956
2018-12-19 18:58
浏览 257
已采纳

xmlhttprequest responsetext为null

I'm trying to make basic HTML Server connection, therfore I want to call and JS function which should call an PHP file just schoing "hello world". Everything is working so far but the response I get seems to be null. I've read through various tutorials but I did not find an answer, hope someone can help me.

            var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status==200 && xhttp.responseText!=null) {
                alert("Responestext: " + xhttp.responseText + "  ENDE");
            }else if(xhttp.status==403){
                alert("forbidden");
            }else if(xhttp.status==404){
                alert("not found");
            }else if(xhttp.responseText==null) {
                alert("response text = null");
            }else{
                alert("Error");
            }
        };
        xhttp.open("GET", "http://URL/fahrgemeinschaft/login.php", true);
        xhttp.send(null);

I expect the output to be "Responsetext: hello world ENDE" but all I get is "Error". I get two alert boxes saying "Error" as well.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doucan8049 2018-12-19 19:06
    已采纳

    The problem is your onreadystatechange handler is called for every ready state change event, not just when it is done.

    You should skip the events that are not done:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState != XMLHttpRequest.DONE) {
            return;
        }
        if (xhttp.status==200 && xhttp.responseText!=null) {
            alert("Responestext: " + xhttp.responseText + "  ENDE");
        }else if(xhttp.status==403){
            alert("forbidden");
        }else if(xhttp.status==404){
            alert("not found");
        }else if(xhttp.responseText==null) {
            alert("response text = null");
        }else{
            alert("Error");
        }
    };
    xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
    xhttp.send(null);
    

    Or to make it easier on yourself, so long as you don't need to support obsolete browsers, just use the onload event.

    var xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
        if (xhttp.status==200 && xhttp.responseText!=null) {
            alert("Responestext: " + xhttp.responseText + "  ENDE");
        }else if(xhttp.status==403){
            alert("forbidden");
        }else if(xhttp.status==404){
            alert("not found");
        }else if(xhttp.responseText==null) {
            alert("response text = null");
        }else{
            alert("Error");
        }
    };
    xhttp.open("GET", "http://messenger.hopto.org:8080/fahrgemeinschaft/login.php", true);
    xhttp.send(null);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题