我正在尝试将一个变量从jQuery传递给一个PHP文件,但我在做这件事时遇到了困难。
这是一个简单的"send.html“文件。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'post',
url: 'receive.php',
data: {
message : "Hello World!",
},
success: function(data) {
//console.log(data);
alert(data);
}
});
});
});
</script>
</head>
<body>
<button>Click here</button>
</body>
</html>我有一个PHP文件"receive.php“。
<?php
$message = $_POST['message'];
echo $message.'<br />';
?>当我点击send.html上的按钮时,我得到了正确的提示"Hello World!“。但是,当我调用receive.php文件时,我收到以下错误消息:
Notice: Undefined index: message in receive.php on line 3有没有人知道这个问题的解决方案?
谢谢。
发布于 2014-01-27 14:59:30
$_POST['message']只有当你通过点击提交按钮进入你的php文件时,这才能在你的receive.php中工作,因为你已经使用ajax来调用你的php文件。但是如果你在没有点击提交按钮的情况下调用receive.php文件,它会给出错误,因为你的php文件中没有任何内容。因此,为了避免此错误,请使用isset()函数:
<?php
if(isset($_POST['message'])){
$message = $_POST['message'];
echo $message.'<br />';
} else {
echo "message not set";
}
?>有关isset()的更多详细信息,请参阅http://in3.php.net/isset
发布于 2014-01-27 14:56:31
删除,在jquery的data参数的值末尾
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'post',
url: 'receive.php',
data: {message : "Hello World!"},
success: function(data) {
//console.log(data);
alert(data);
}
});
});
});发布于 2014-01-27 15:07:23
ajax请求应该如下所示:
$.ajax({
type: "POST",
url: "receive.php",
data: { message: "Hello World"}
})
.done(function(data) {
alert(data);
})尝试使用done结构而不是success,因为它现在已被弃用。就receive.php文件而言,请确保在url参数中正确设置了路径,并且最佳实践应位于receive.php文件中:
<?php
$message = "NULL";
if(isset($_POST['message']))
$message = $_POST['message'];
echo $message.'<br />';
?>这样,当您运行pull up receive.php文件时就不会得到Undefined index message error,而且在一定程度上还可以帮助您对其进行调试。希望能有所帮助。
https://stackoverflow.com/questions/21374666
复制相似问题