使用ajax发送JS变量,但是如何在之后使用PHP变量到我的主文件?

时间:2014-08-07 11:28:07

标签: javascript php

如何使用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"

4 个答案:

答案 0 :(得分:0)

试试这个

的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();
}

答案 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 中传递多个值/变量。所以

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