使用ajax发送一个JS变量,但我怎么能使用PHP变量之后到我的主文件

Using ajax to send a JS variable, but how can I use PHP variables afterwards to my main file?

本文关键字:变量 怎么能 PHP 之后 主文件 我的 使用 JS 一个 ajax      更新时间:2023-09-26

如何使用一些PHP变量从ajax-send.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"

试试这个

Ajax

$.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
    }
});
PHP

if(isset($_POST['one'])){
   $token = $_POST['one'];
   echo "ok";
   $toINDEX = "use this in index.php";
   die();
}

在PHP中只是echo变量或json_ encode数组。在JS中执行以下操作:

var result = $.ajax({
  url: this.fileUrl,
  type: "POST",
  data: data,
  async: false,
  dataType: 'json'
}).responseText;

你的变量是完全可访问的

获取PHP会话中的变量

    //On page 1(ajax-send.php)
    session_start();
    $_SESSION['token'] = $_POST['one'];
    //On page 2(index.php)
    session_start();
    $var_value = $_SESSION['token'];

您可以简单地echo变量,然后通过success函数内的javascript访问它。

但是更好的方法是json_encode数据。这样做的美妙之处在于它将帮助您在单个echo 中传递多个值/变量。所以

PHP

.
..
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);
Javascript

$.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);
相关文章: