weixin_33735077 2016-07-18 18:05 采纳率: 0%
浏览 9

Ajax Post与GET

I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!

HTML & JavaScript:

<html>
    <head>
        <title> Create a new user</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script>  

            function checkUser(){
                xhttp = new XMLHttpRequest();
                xhttp.open("POST","usercheck.php",true);

                                xhttp.onreadystatechange = function () {
                                    if (xhttp.readyState == 4 && xhttp.status == 200) {
                                        var data = xhttp.responseText;
                                        alert("Benutzer" + data);
                                    }
                                }
                                xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
                            }

        </script>
    </head>
    <body>
        <p>User:</p><br> 
        <input type="text" id="username" name="username">
        <button onclick="checkUser();"> Check </button>
    </body>
</html>

PHP Code:

<?php

$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";

if (!isset($_POST["username"])) {
    die("{valid:false,message:false}");
}

if (in_array($_POST["username"], $usernames)) {
    die("{valid:false,message:'Username is used!'}");
}

if (!preg_match($validate_pattern, $_POST["username"])) {
    die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";


 ?>
  • 写回答

1条回答 默认 最新

  • weixin_33721427 2016-07-19 14:14
    关注

    I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately: xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');

    评论

报告相同问题?

悬赏问题

  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥15 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?