I'm a designer who dabbles in scripting using JQuery and PHP. I have a pretty good understanding of functionality in both but using sessions is new to me.
I have an app with a search feature. The search results may stretch over several pages and each result has a checkbox. The idea is the user goes through the results and checks off items they want, then the result is outputted to a PDF for which there's a button at the bottom of each page. So I need to be able to keep track of the items the user has checked off between pages.
T开发者_运维知识库he method I'm using is to keep track of the checked items using an array stored in the $_session. Each time an item is checked JQuery sends the ID to an session.php file using $.post and the idea is that session.php pushes that into the session-stored array, and the opposite for unchecking an item. When the 'convert to pdf' button is clicked JQuery grabs the array from session.php and sends it to another php page that uses the IDs to query and does all the PDF conversion stuff.
Where the gaps in my knowledge fail me are how I can get the array back to JQuery in a usable form. I have it working by sending back and forth a comma delimited string version of the array using this:
foreach($_SESSION["idsArray"] as $value) {
$sendme .= $value.",";
}
echo $sendme;
I can take that data and break it out in JQuery but I wonder if because of my limited knowledge I'm missing something that would keep the array intact?
Thanks.
I think, if I understand your question correctly, what you're looking for is json_encode(). If you do a json_encode($_SESSION['idsArray'])
then you can fetch that with $.ajax() and set the dataType to 'json'. Then the array will automatically be turned into a JavaScript array.
First off, you can use the php function implode() to get the the array into string format.
Even better though, you can send the array to jQuery through JSON, as Darrell said, or also as plain html in <script>
tags and then using the javascript function eval()
to turn it into an array that jQuery can use. The PHP would look something like:
echo '<script type="text/javascript">
var newArray = new Array();';
foreach($_SESSION['idsArray'] as $value){
echo 'newArray.push('.$value.');';
}
echo '</script>';
The javascript would look like this:
$.post(..., function(data){
eval(data);
//you can now use the array
});
精彩评论