我试图找出为什么我使用的同一段代码不能使用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
非常感谢你。
答案 0 :(得分:0)
您的Ajax代码很好,您只需要在使用PHP Super Global($_POST
)之前添加一个检查:
if(count($_POST) > 0){
$name = $_POST["user"];
echo ("The name is : ".$name );
}
else{
echo "Name not found";
}
您也可以使用isset()
功能设置$_POST
设置或不设置。
答案 1 :(得分:-2)
更改
data: {user : userName}
要
data: {'user' : userName}