2013-03-15 35 views
1

我打電話的功能,並保存在這個功能我發送一個$。員額爲「upp.php」:JSON解碼未定義指數

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> 

是的,我得到這一切,但信息是有,但它也顯示其他信息

+2

並把__var_dump($ _ POST); __在upp.php中輸出什麼? – Waygood 2013-03-15 16:28:59

+0

出來陣列(0){} – Bash 2013-03-15 16:42:42

+0

所以你的帖子是空的。看看@Quentin關於重定向的說法。你應該看看你的$ .post – Waygood 2013-03-15 16:51:33

回答

3

您的Ajax請求成功後你window.location.href = "upp.php";這使得GET請求相同的URL。

由於它是一個GET請求,$_POST是空的,所以應該預期錯誤。

測試以查看$_POST['items']是否爲數組鍵並分支您的兩種狀態的代碼。

+0

哦,我看到了,對不起,我是JavaScript新手我怎麼能測試這個|? – Bash 2013-03-15 16:31:59

+0

這是PHP,而不是JavaScript。 http://php.net/array_key_exists – Quentin 2013-03-15 16:32:57

+0

我仍然得到一個未定義的索引 – Bash 2013-03-15 16:43:00

0

爲什麼你要轉換爲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']; 
+0

但它會在localStorage數組中有多個值?任何想法如何運行一個循環來解決這個問題? – Bash 2013-03-15 16:48:36