【问题标题】:PHP sends answer twicePHP 发送两次答案
【发布时间】:2020-10-23 17:48:32
【问题描述】:

我对 Nodejs 有一些经验,所以我也想尝试一些 php。 我想在 php 文件中发出 GET 请求并得到响应。当我获取数据时,我收到了两次。我检查了浏览器上的网络选项卡,我只看到一个请求。 html/javascript 代码在 nodejs 上没有问题,php 坚持发送数据两次。为什么会这样?

HTML 文件:

<html>

<head>
    <title>Hello World</title>
</head>

<body>
    <p>Hello User!!</p>
    <button id="button">Get Request</button>
</body>

<script>
    document.getElementById("button").onclick = function () {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "test.php?id=HI", true);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4 || this.status === 200) {
                console.log(this.responseText);  
            }
        };
        xmlhttp.send();
    };
</script>

</html>

test.php 文件:

<?php
ini_set('display_errors', 1);
    $id = $_GET["id"];
    if($id == "HI"){
        echo ("Noice!");
    }else {
        echo ("I am sowwy :3");
    }
?>

免责声明:“我知道这段代码没有做任何重要的事情,并且总是发送相同的响应。这只是一个让我熟悉 php 的实验”。

感谢您的宝贵时间。

【问题讨论】:

  • if (xmlhttp.readyState === 4 && this.status === 200)

标签: php html onclick xmlhttprequest echo


【解决方案1】:

您不是两次发送响应,而是记录两次。

onreadystatechange 应该是:

xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState === 4) {
    if (this.status === 200) console.log(this.responseText);  
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多