Json解码未定义索引

json decode undefined index

本文关键字:索引 未定义 解码 Json      更新时间:2023-09-26

我正在调用一个保存函数,在这个函数中我正在发送一个$。Post到'up .php':

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) {

在upp.php我使用:

<?php 
$array = json_decode($_POST['items'], True);
foreach ($array as $key=>$line) {
}
?>

,但我得到一个未定义的索引'项目'

编辑:

发布响应后得到的内容

<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css.css" media="all">
<meta name="viewport" content="initial-scale=1.0"/>
<script src="alan.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Data Collection</title>
</head>
<body>
<!--Wrapper-->
<div id="wrap">
<!--Header-->
<div id="header">
<h1> Data Collection </h1>
</div>

<div id="menu">
    <ul>
        <li><a href="homepage.php">Home</a></li>
        <li><a href="comment.php">Comments</a></li>
        <li><a href="logout.php">Logout</a></li>
    </ul>
</div><input type="text" id="data"/>

<div id="heading">
<h3> Welcome, alan </h3>
</div>
array(1) {
  ["items"]=>
  string(167) "[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]"
}

<div id="footer">
<h1> Footer </h1>
</div>
</div> <!--End of wrapper-->
</body>
</html>

是的,我得到了所有这些但是信息在那里但是它也显示了其他信息

Ajax请求成功后,您的window.location.href = "upp.php";将向相同的URL发出GET请求。

因为它是一个GET请求,$_POST是空的,所以错误应该是预料之中的。

测试$_POST['items']是否为数组键,并为这两种状态分支代码

你为什么要转换成JSON来写一篇文章?为什么不直接使用jQuery序列化表单并发布,那么您就可以在PHP中使用该对象,而无需任何额外的工作。

html…

<form id="myForm">
   <input name="q1"></input>
   <input name="q2"></input>
   ...
</form>

* js… *

var formdata = $("#myForm").serialize();
$.ajax({
   type:'POST',
   url:'upp.php',
   data:formData,
   success:function(){ /* ... */ }
});
php…

echo $_POST['q1'];
echo $_POST['q2'];