I have a simple example of PHP sessions and AJAX, which works when holding an array in session:
Request file:
<?php
session_start();
$_SESSION['data'] = array('foo','bar');
echo count($_SESSION['data']);
?>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
</head>
<body>
<button id="but1">Go<开发者_JS百科/button>
<script type="text/javascript">
$('#but1').click(function() {
$.ajax({
url:'ajaxtest_remote.php',
success:function(result) {
alert(result);
}
});
});
</script>
</body>
</html>
Remote file:
<?php
session_start();
echo 'count=' . count($_SESSION['data']);
?>
The echo on the first file shows 2, and the alert in the success function displays "count=2". Happy days.
Where the problem happens is if I swap my array for a class object:
Request File:
<?php
session_start();
include('ajaxtest_class.php');
$_SESSION['obj'] = new TestClass('foo,bar');
echo count($_SESSION['obj']->dataList);
?>
<!-- HMTL AS ABOVE -->
Remote File:
<?php
session_start();
echo 'count=' . count($_SESSION['obj']->dataList);
?>
Class File:
<?php
class TestClass {
var $dataList;
function TestClass($incoming) {
$this->dataList = explode(',',$incoming);
}
}
?>
This still displays a 2 on the first page, but the ajax success alert comes back "count=0". Can anyone explain why this is?
Update1
If I import the class file into remote it still doesn't work, although I can prove the class is loaded.
<?php
session_start();
include('ajaxtest_class.php');
$c = new TestClass('a,b,c');
echo 'count=' . count($_SESSION['obj']->dataList) . '-' . count($c->dataList);
?>
The new alert from the ajax success reads count=0-3
.
Update2
var_dump($_SESSION['obj']);
object(__PHP_Incomplete_Class)#8 (2) {
["__PHP_Incomplete_Class_Name"]=>
string(9) "TestClass"
["dataList"]=>
array(2) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
}
}
You would need to include the Class in the remote_ajax file (before session_start()
):
edit: The serialize/unserialize requirement is a limitation of PHP4.
Request file:
<?php
include('ajaxtest_class.php');
session_start();
$_SESSION['obj'] = serialize(new TestClass('foo,bar'));
Remote file:
<?php
session_start();
include('ajaxtest_class.php');
$obj = unserialize($_SESSION['obj']);
echo 'count=' . count($obj->dataList);
?>
In PHP, the class constructor should be defined differently:
<?php
class TestClass {
var $dataList;
function __construct($incoming) {
$this->dataList = explode(',',$incoming);
}
}
?>
精彩评论