在jquery中由ajax在php数组/会话中存储值

时间:2013-06-28 06:57:58

标签: php jquery ajax

我想在jquery中通过ajax在PHP数组或PHP会话中存储值 我在php页面上通过ajax发送一些值并想要存储它们

问题:每次数组/会话返回最新发送的值,而不是我发送的先前值 我希望以前发送的值应该保留在数组或会话中

我的代码在

下面

Js文件代码

$.ajax({
                url: "http://domain.com/ajax.php",
                type:"POST",
                data: { name : nname , 
                    clas : nclass , 
                    rows : nrows ,
                    cols : ncols , 
                    types : ntype , 
                    check : ncheck , 
                    count : ncldiv
                 },

            success: function(data){
             alert(data); 
           }
            });

PHP文件

<?php
        session_start(); 
        $_SESSION['feilds'] = array();    
        $type = $_POST['types'];
        $name = $_POST['name'];
        $class = $_POST['clas'];
        $rows = $_POST['rows'];
        $cols = $_POST['cols'];
        $check = $_POST['check'];
        $count = $_POST['count'];
         $output_string = array('TYPE'=>$type,'NAME'=>$name,'CLASS'=>$class,'ROWS'=>$rows,'COLS'=>$cols,'REQUIRED'=>$check);
        array_push($_SESSION['feilds'] , $output_string );
        print_r($_SESSION['feilds']);
?>

3 个答案:

答案 0 :(得分:0)

由于$_SESSION['feilds'] = array();而发生这种情况。

调用页面时$_SESSION['feilds']分配空白数组。这就是为什么你只获得当前值。

使用$_SESSION['feilds']isset

检查empty是否已存在
if(empty( $_SESSION['feilds'] )) {
  $_SESSION['feilds'] = array();
}

答案 1 :(得分:0)

问题是您始终将$_SESSION['feilds']变量实例化为空白数组。使用此:

<?php
    session_start(); 
    if (!isset($_SESSION['feilds'])) {
        $_SESSION['feilds'] = array();
    }
    $type = $_POST['types'];
    $name = $_POST['name'];
    $class = $_POST['clas'];
    $rows = $_POST['rows'];
    $cols = $_POST['cols'];
    $check = $_POST['check'];
    $count = $_POST['count'];
     $output_string = array('TYPE'=>$type,'NAME'=>$name,'CLASS'=>$class,'ROWS'=>$rows,'COLS'=>$cols,'REQUIRED'=>$check);
    array_push($_SESSION['feilds'] , $output_string );
    print_r($_SESSION['feilds']);
?>

答案 2 :(得分:0)

    you wrote  $_SESSION['feilds'] = array();
    Every time it  assign a empty array at session so it will wash out previous data. 
if you want to retain your previous data then first add check like 
        if(empty( $_SESSION['feilds'] )) {
          $_SESSION['feilds'] = array();
        }
        after that you assign value to session as you are doing 
hope it will help you :)