无法在 php 中获取 POST 数据“未定义索引”错误


unable to get POST data in php 'undefined index' error

我正在使用纯JavaScript进行Ajax请求。 当通过 post 方法 PHP 发送数据时抛出错误。

索引.php

<html>
    <header>
        <script>
            function submit(){
                var userName = document.getElementById("username").value;
                var passWord = document.getElementById("password").value;

                var data = "username=" + userName + "&password=" + passWord;
                //send ajax request
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.onreadystatechange = function()
                {
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    {
                        console.log(xmlHttp.responseText);
                    }
                }
                xmlHttp.open("post", "validateuser.php");
                xmlHttp.send(data);
            }
        </script>
    </header>
    <body>
            <label>User Name : </label>
            <input type="text" name="username" id="username"/>
            <label>Password : </label>
            <input type="text" name="password" id="password"/>
            <button onClick="submit()"> Login</button>
    </body>
</html>

验证用户.php

<?php
    $userName = $_POST["username"];
    $password = $_POST["password"];
echo $userName . $password;

在 Javascript ajax for post 中,您需要在代码中添加以下行:

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

您可以查看文档和示例 W3schools 和开发人员 Mozilla

对于更可靠的代码,只需在 php 代码
中添加以下行

if(isset($_POST['username']) && isset($_POST['password'])){
     //your code
}
您需要

xmlHttp对象上设置标头。在xmlHttp.send(data);行之前添加以下行:

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");