如何使用ajax-send.php中的一些PHP变量到index.php文件?我使用AJAX,如下所示。我是否必须用其他东西替换AJAX?
的index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
Ajax的send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
答案 0 :(得分:0)
试试这个
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
答案 1 :(得分:0)
在PHP中只有echo
变量或json _ encode
数组。在JS
中执行以下操作:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
您的vaiable完全可以访问。
答案 2 :(得分:0)
获取php会话中的变量
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
答案 3 :(得分:0)
您可以简单地echo
变量,然后通过success
函数中的javascript访问它。
但更好的方法是json_encode
数据。这样做的好处在于它可以帮助您在单个echo
中传递多个值/变量。所以
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
这里要注意的重要事项是dataType:'json'
,它告诉函数以json
格式预期返回的数据。
修改强>
根据你的评论,你可以这样做
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);