Ajax GET在同一段代码上工作,但不能POST


Ajax GET is working but not POST on the same piece of code

我正在努力找出为什么我使用的同一段代码不适用于POST方法,但它完全适用于GET。以下是我的代码:

<head>
     <meta charset="UTF-8">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
    <form id="contact">
        <input id="name" name="name"/>
        <input name="email_address"/>
        <textarea name="message"/></textarea>
        <button id="submit"/>Submit</button>
    </form>
    <script>
        $( function(){
            $('#contact').submit( function(e){
              e.preventDefault();
              var userName= $("#name").val();
              console.log(userName);
                $.ajax({
                    type: "POST",
                    url:  "submitContact.php",
                    data: {user : userName} ,
                    success: function( data ){
                        console.log( data );
                    }
                });
            });
        });
    </script>
</body>

这是我的PHP代码片段(称为submitContact.PHP),我正试图从Ajax请求中检索userName并将其打印出来

$name = $_POST["user"];
echo ("The name is : ".$name );
echo   ("   Method Used:").$_SERVER['REQUEST_METHOD'];

然而,当我填写表单并将正确的数据发送到服务器时,当我尝试使用POST方法时,我得到的回复如下。奇怪的是,使用GET,它的工作方式与预期完全一样。

<br />
<b>Notice</b>:  Undefined index: user in <b>C:'Users'Panagiotis'PhpstormProjects'test2'submitContact.php</b> on line <b>11</b><br />
The name is :    Method Used:POST

事先非常感谢。

您的Ajax代码很好,您只需要在使用PHP Super Global($_POST)之前添加一个检查即可:

if(count($_POST) > 0){
   $name = $_POST["user"];
   echo ("The name is : ".$name );
}
else{
   echo "Name not found";
}

您也可以使用isset()函数,无论是否设置$_POST

更改

 data: {user : userName} 

 data: {'user' : userName}