使用session通过ajax调用将变量从HTML文件中的jQuery传递到php文件
I am trying to pass a variable from jQuery to a PHP file and I am having a difficulty in doing it.
Here is a simple HTML file of "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!"}
})
.done(function(data) {
alert(data);
});
});
});
</script>
</head>
<body>
<button>Click here</button>
</body>
</html>
And I have a PHP file of "receive.php".
<?php
session_start();
if(isset($_POST['message'])){
$_SESSION['message'] = $_POST['message'];
echo $_SESSION['message'].'<br />';
} else {
echo "message not set";
}
?>
When I click the button on send.html, I get the correct alert saying "Hello World!". But when I access "receive.php" by typing the URL on my webbrowser, I get the message saying:
message not set
If I want to get "Hello World!" from receive.php, what should I do? Anybody has a solution to this problem?
Thanks.
我正在尝试将变量从jQuery传递给PHP文件,我很难做到这一点。 / p>
这是一个简单的“send.html”HTML文件。 p>
&lt; html&gt;
&lt; head&gt;
&lt; script src =“http://code.jquery.com/jquery-1.10.1.min.js”&gt;&lt; / script&gt;
&lt; script&gt;
$(document).ready(function(){
$(“button”)。click(function(){
$ .ajax({
type:'post',
url:'receive.php',
data:{message:“Hello World!” }
})
.done(function(data){
alert(data);
});
});
});
&lt; / script&gt;
&lt; / head&gt; \ n&lt; body&gt;
&lt; button&gt;点击此处&lt; / button&gt;
&lt; / body&gt;
&lt; / html&gt;
code> pre>
我有一个PHP 文件“receive.php”。 p>
&lt;?php
session_start();
if(isset($ _ POST ['message'])){
$ _SESSION ['message'] = $ _POST ['message'];
echo $ _SESSION ['message']。'&lt; br /&gt;';
} else {
echo“message 没有设置“;
}
?&gt;
code> pre>
当我点击send.html上的按钮时,我收到正确的警告”Hello World!“ 。 但是当我通过在我的webbrowser上输入URL来访问“receive.php”时,我得到的消息是: p>
消息未设置
code> pre>
如果我想获得“Hello World!” 来自receive.php,我该怎么办?
任何人都有解决这个问题的方法吗? p>
谢谢。 p>
div>
your receive.php should be
<?php
session_start();
if(isset($_POST['message'])){
$_SESSION['message'] = $_POST['message'];
echo $_SESSION['message'].'<br />';
}else if(isset($_SESSION['message'])){
echo $_SESSION['message'].'<br />';
}else{
echo "message not set";
}
?>