![](/img/trans.png)
[英]jQuery ajax pass variable to php session, but php session not store it
[英]store values in php array/session by ajax in jquery
我想通過ajax在jquery中將值存儲在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']);
?>
這是由於$_SESSION['feilds'] = array();
。
當頁面被調用時, $_SESSION['feilds']
被分配空白數組。這就是為什么您只獲得當前值的原因。
通過使用isset
或empty
來檢查$_SESSION['feilds']
是否存在
if(empty( $_SESSION['feilds'] )) {
$_SESSION['feilds'] = array();
}
問題是您總是將$_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']);
?>
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 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.