Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Ajax、PHP中传递变量_Php_Jquery_Ajax - Fatal编程技术网

如何在Ajax、PHP中传递变量

如何在Ajax、PHP中传递变量,php,jquery,ajax,Php,Jquery,Ajax,我使用PHP已经快一年了,但是我遇到了一个困扰我好几天的问题。正如我们所知,我们可以使用Ajax将变量传递给PHP,然后返回响应进行显示。但是我如何从一个代码块到另一个代码块获取变量呢?让我在代码中描述我的问题。因为我的代码非常大,所以我在这里放了一个简化版本 <?php $array = [1,2,3,4,5]; //first Ajax call if(isset($_POST['id'])){ $id = $_POST['id']; $value= $_POST[

我使用PHP已经快一年了,但是我遇到了一个困扰我好几天的问题。正如我们所知,我们可以使用Ajax将变量传递给PHP,然后返回响应进行显示。但是我如何从一个代码块到另一个代码块获取变量呢?让我在代码中描述我的问题。因为我的代码非常大,所以我在这里放了一个简化版本

<?php
  $array = [1,2,3,4,5];
//first Ajax call
if(isset($_POST['id'])){
    $id = $_POST['id'];
    $value= $_POST['value'];
    $array[$id] = value; //The first call is mainly to update the value of $array
    echo $value;
    exit();
}

//Second Ajax call
if(isset($_POST['name'])){
     print_r($array);   //I want to use $array here, but I got the original 
     .....              //one.So what should I do to get the updated $array 
                        //from last Ajax call? 
}

对页面的AJAX调用每次都初始化一组新的变量。您无法从连续调用中访问$arrray,但可以访问会话变量

添加
session_start()在页面顶部,然后

<?php
//first Ajax call
if(isset($_POST['id'])){
     $_SESSION['id'] = $_POST['id'];
     $_SESSION['value'] = $_POST['value'];         //The first call is mainly to update the value of $array
     echo $_SESSION['value'];
     exit();
}

//Second Ajax call
if(isset($_POST['name'])){
    echo $_SESSION['id'],"<br>";
    echo $_SESSION['value'],"<br>";
}

您需要一些永久性存储,例如数据库,或者如果您只是想暂时使用
$\u SESSION[]
在整个会话中保存数据(请参见)…您忘记了一堆结尾分号Mike;-)哦,麻烦-我今天洗了手,我一点也做不到:(呵呵,没问题。是时候从棕榄转向阳光了;-)是的。就是这样,它类似于购物车的代码。非常感谢,伙计