我对您的评论的回复(如何在 AJAX 中执行此操作):
这是一种混乱的方式,但这会给你(我认为)你想要的结果:
索引.php:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>AJAX</title>
<style>
.obj {
padding:15px 15px;
background:red;
}
</style>
</head>
<body>
<div class="obj">Click Me</div>
<ul class="items">
</ul>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function() {
//Retrieve current SESSION li tags
$.ajax({
type : 'POST',
url : 'ajax.php',
success: function(data) {
var json = $.parseJSON(data);
$.each(json, function(i, serverData) {
$('.items').append('<li class="item">' + serverData + '</li>');
});
}
});
//add li tags and store to session
var counter = 0;
$('.obj').on('click', function() {
counter++;
$('.items').append('<li class="item">Foo' + counter + '</li>');
var form_data,
li_array = new Array();
$('.item').each(function() {
li_array.push( $(this).html() );
});
form_data = {
data : li_array
};
//set.php sets the SESSION data and appends the li tags to it for future reference
$.ajax({
type : 'POST',
url : 'set.php',
data : form_data
});
});
});
</script>
</body>
</html>
ajax.php:
<?php
session_start();
echo json_encode($_SESSION['li']);
?>
设置.php:
<?php
session_start();
$_SESSION['li'] = array();
foreach ($_POST['data'] as $data) { array_push($_SESSION['li'], $data); }
echo json_encode($_SESSION['li']);
?>
注意:这将保留 li 标签。取消它们的方法是清除会话。