簡體   English   中英

無法獲取php'undefined index'錯誤中的POST數據

[英]unable to get POST data in php 'undefined index' error

我正在對Ajax請求使用普通的javascript。 通過post方法php發送數據時拋出錯誤。

index.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>

validateuser.php

<?php

    $userName = $_POST["username"];
    $password = $_POST["password"];

echo $userName . $password;

在用於發布的Javascript ajax中,您需要在代碼中添加以下行:

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.send(data); 行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM