AJAX没有通过javascript进行响应

AJAX not echoing through javascript

本文关键字:响应 javascript AJAX      更新时间:2023-09-26

好的,所以我正在尝试让PHP将用户数据保存到XML中,然后将用户转发到主页上。。但当运行JavaScript时,它不会在脚本末尾捕获echo和header();

PHP我希望回声

  echo "<b>Congratulations registration was Successful.<br /> Your Customer ID is: $id4</b>";
          echo "<br/>";
          echo "redirected automatically in 7 seconds";
            header( "Refresh:7; buyonline.htm", true, 303);
          $doc->save("data/customer.xml");
        }

以及JavaScript函数

    var firstname = document.getElementById("firstName").value;
            var lastname = document.getElementById("lastName").value;
            var email = document.getElementById("email").value;
            var password = document.getElementById("password").value;
            var password2 = document.getElementById("password2").value;
            var number = document.getElementById("pNumber").value;
            var type = "";
            var input = document.getElementsByTagName("input");
              xHRObject.open("GET", "testregristation.php?firstName=" + firstname + "&lastName=" + lastname + "&email=" + email + "&password="+password+"&pNumber="+number, true);
              xHRObject.onreadystatechange = function() {
                   if (xHRObject.readyState == 4 && xHRObject.status == 200)
                    {
                       document.getElementById('information').innerHTML = xHRObject.responseText;
                    }
              xHRObject.send(null); 

显然,这些都是小片段,但我不明白为什么它不会将响应发送到屏幕上——它以"firebug"显示响应。。我的PHP还做了一个电子邮件检查,以确保它没有被使用,这一点得到了完美的回应。

我还没有真正测试过你的代码,以确保我要说的是100%正确的。我从未尝试过在ajax响应中以这样的方式使用header。但是,我想如果您想重定向用户,只需使用javascript即可。

PHP:

echo "<b>Congratulations registration was Successful.<br /> Your Customer ID is: $id4</b>";
echo "<br/>";
echo "redirected automatically in 7 seconds";
$doc->save("data/customer.xml");

Javascript:

if (xHRObject.readyState == 4 && xHRObject.status == 200)
{
    document.getElementById('information').innerHTML = xHRObject.responseText;
    setTimeout(function()
    {
        window.location.pathname = "/buyonline.htm";
    }, 7000 /* 7 seconds */);
}

编辑:现在,因为您使用javascript重定向页面,您还可以倒计时秒数:

PHP:

echo "<b>Congratulations registration was Successful.<br /> Your Customer ID is: $id4</b>";
echo "<br/>";
echo "redirected automatically in <span id="redirect-countdown">7 seconds</span>";
$doc->save("data/customer.xml");

Javascript:

if (xHRObject.readyState == 4 && xHRObject.status == 200)
{
    document.getElementById('information').innerHTML = xHRObject.responseText;
    var countdown = document.getElementById("redirect-countdown");
    var count = 8;
    var interval = setInterval(function()
    {
        count--;
        countdown.innerText = count + " second" + (count > 1 ? "s" : "");
        if(count <= 0)
        {
            clearInterval(interval); // Kill the interval timer
            window.location.pathname = "/buyonline.htm"; // Redirect to that page
        }
    }, 1000);
}