【问题标题】:Getting status of XMLHttpRequest variable from PHP从 PHP 获取 XMLHttpRequest 变量的状态
【发布时间】:2016-02-19 23:01:50
【问题描述】:

我的问题是 PHP 的 var 是 1,但 JavaScript 不希望我给我 var 1 的相应状态。我对 JavaScript 没有什么经验,很抱歉代码很糟糕。

function plzcheck(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "Login/plzcheck.php";
    var plz = document.getElementById("Postleitzahl").value;
    var vars = "plz="+plz;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = 'progressing...'
}  
hr.onreadystatechange = function() {
    if(return_data == 1){
        hr.onreadystatechange = function() {                
            $('.containerlogin').stop().addClass('active');
            document.getElementById("status2").innerHTML = "Deine PLZ ist Verfügbar!";
        }
    } else {                    
        hr.onreadystatechange = function() {        
            $('.containerlogin').stop().addClass('active');
            document.getElementById("status2").innerHTML = "Leider ist deine PLZ noch nicht Verfügbar. Registriere dich und wir geben dir bescheid, wenn es losgeht!";
        }
    }
}

这里出了什么问题?我希望收到第一条消息,但我总是收到最后一条:“Leider ist deine...”

【问题讨论】:

  • 至少正确缩进你的代码。
  • 为什么你不断地覆盖onreadystatechange? hr.onreadystatechange = function() {。另外,既然您似乎在使用 jQuery,为什么不使用 jQuery.ajax 方法
  • 感谢您的建议!我将使用 jquery

标签: javascript php jquery xmlhttprequest


【解决方案1】:
hr.onreadystatechange = function() {
$('.containerlogin').stop().addClass('active');


if(hr.responseText == "plzda"){



      document.getElementById("status2").innerHTML = "Deine PLZ ist Verfügbar!";

                 } else {   


        document.getElementById("status2").innerHTML = "Leider ist deine PLZ noch nicht Verfügbar. Registriere dich und wir geben dir bescheid, wenn es losgeht!";
     }
 }

     }     

解决了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2014-02-02
    • 2014-06-10
    相关资源
    最近更新 更多