我正在尝试将变量从 jQuery 传递到 PHP 文件,但我在做这件事时遇到了困难。
这是“send.html”的简单 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>
我有一个“receive.php”的 PHP 文件。
<?php
$message = $_POST['message'];
echo $message.'<br />';
?>
当我点击 send.html 上的按钮时,我得到了正确的提示“Hello World!”。 但是当我调用 receive.php 文件时,我收到以下错误消息:
Notice: Undefined index: message in receive.php on line 3
有谁知道这个问题的解决方案吗?
谢谢。
最佳答案
$_POST['message']
这只会在您的 receive.php
中起作用,因为您使用了 ajax,因此只有当您通过单击提交按钮转到您的 php 文件时用于调用您的 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
关于php - 将变量从 HTML 文件中的 jQuery 传递到 PHP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21374666/