简体   繁体   English

从localStorage检索然后在php中使用

[英]retrieving from localStorage then using in php

I have a multidimensional array ($order). 我有一个多维数组($ order)。

echo json_encode($order); 回声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? 我将其存储在我认为正确的localStorage中?

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

a) How do I retrieve it from localStorage? a)如何从localStorage检索它?

b) And then how do I use it in php? b)然后如何在php中使用它?

localStorage stores strings, not structured objects. localStorage存储字符串,而不是结构化对象。 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. 如果要存储JSON对象,请使用localStorage["mything"] = JSON.stringify(myvar) ,然后从localStorage(绑定到各个页面)中检索它,请使用JSON.parse(localStorage["mything"])

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. 不使用JSON.stringify意味着您将存储字符串“ [Object object]”或类似的东西,因为JavaScript会将您的对象强制转换为字符串,并完全出于您的目的而将其弄错了。

this line: 这行:

var array = "<?php echo(json_encode($order)); ?>"; 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}]"; 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)); var myArray ='<?php echo(json_encode($ order)); ?>'; ?>';

now you will have a proper string to store into localstorage with: 现在您将拥有一个适当的字符串,可以使用以下方式存储到本地存储中:

localStorage.setItem('myArray', myArray); localStorage.setItem('myArray',myArray);

you can then retrieve it from localstorage with: 然后,您可以使用以下方法从本地存储中检索它:

myArray = localStorage["myArray"]; 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. 但是,正如totymedii所建议的那样,在php中使用数组的最佳选择是通过ajax调用将其发送到服务器。

-C -C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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