简体   繁体   中英

retrieving from localStorage then using in php

I have a multidimensional array ($order).

echo json_encode($order); produces the output below so that you can see the structure:

[{"rank":5,"day":1},{"rank":4,"day":1},{"rank":1,"day":2},{"rank":3,"day":2},{"rank":2,"day":2}] 

I'm storing it in localStorage which I think is correct?

var array = "<?php echo(json_encode($order)); ?>";
localStorage.setItem('array', array);

a) How do I retrieve it from localStorage?

b) And then how do I use it in php?

localStorage stores strings, not structured objects. If you want to store a JSON object, use localStorage["mything"] = JSON.stringify(myvar) , and then to retrieve it from localStorage (which is bound to individual pages), use JSON.parse(localStorage["mything"]) on the same page.

Not using JSON.stringify means you'll be storing the string "[Object object]" or something similar, because JavaScript will coerce your object into a string and get it completely wrong for your purpose.

this line:

var array = "<?php echo(json_encode($order)); ?>";

is producing a string:

var array = "[{"rank":5,"day":1},{"rank":4,"day":1},{"rank":1,"day":2},{"rank":3,"day":2},{"rank":2,"day":2}]";

but the string will break because of nested quotes.

the line should be written with single quotes:

var myArray = '<?php echo(json_encode($order)); ?>';

now you will have a proper string to store into localstorage with:

localStorage.setItem('myArray', myArray);

you can then retrieve it from localstorage with:

myArray = localStorage["myArray"];

But then, as totymedii suggests, your best bet for using the array in php is to send it to your server in an ajax call.

-C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM