将Javascript数组保存到PHP

时间:2013-03-15 15:26:07

标签: php javascript

你好我对javascipt很新,所以请清楚地解释一下。我目前正在运行一个php页面,其中包括:

upp.php     

<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>

此items数组包含保存的对象:

function save(){

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {};
var num = document.getElementById("num").value;

newItem[num] = {
    "methv": document.getElementById("methv").value
    ,'q1': document.getElementById("q1").value,
    'q2':document.getElementById("q2").value,
    'q3':document.getElementById("q3").value,
    'q4':document.getElementById("q4").value,
    'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}

$.post('upp.php',{ items: JSON.stringify(oldItems) }, function(response) {
    window.location.href = "upp.php";

页面的结果如下所示:

[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]

无论如何我可以将这些信息保存到PHP中并拆分数据,这样我就可以像循环一样一次操作一个。例如:

第一次:

{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}

下一步:

{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}

感谢。

1 个答案:

答案 0 :(得分:1)

<强> upp.php:

<?php 
$array = json_decode($_POST['items'], True);
foreach ($array as $key=>$line) {
    # $key is a number like 1173627548
    # and $Line is an array with methv, q1, q2, q3, q4, and comm
}
?>

这将显示它从JSON获得的数组。现在您可以处理数据了。