2011-03-10 56 views
0

我用jQuery收集數據,把它放到一個多維數組中,使用JSON.stringify並通過AJAX傳遞給PHP,由於某種原因json_decode不斷給我一個Syntax error, malformed JSON錯誤。通過Ajax到php的多維數組通過json_decode變成null

是被傳遞給PHP

[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]] 

奇怪的

繼承人的JSON是,我使用JSON.stringify在JS多維陣列上。繼承人如何我把它放在一起

var dataz = []; 
var arrayContainingAll = []; 

$("li", "#ingredientlist").each(function() { 
    var tempArray = []; 
    tempArray.push($(".ingredientname", this).text()); 
    tempArray.push($(".unittext", this).text()); 
    tempArray.push($(".amounttext", this).text()); 
    arrayContainingAll.push(tempArray); 
}); 

dataz.push($("h1").text()); 
dataz.push($("#method").val()); 
dataz.push(arrayContainingAll); 
var json = JSON.stringify(dataz); 

我怎樣才能讓PHP正確解析多維數組? 我已經通過在3個不同的字符串化陣列固定它,但它更多的爲什麼多維數組失敗

PHP的顯示會發生什麼好奇的是:var_dump(json_decode($_POST['ingredients']));

,因爲它appearantly重要的是要展示如何我發佈的數據,繼承人的JS做Ajax請求

$.ajax({ 
    url: '/api/savenewrecipe.php', 
    type: 'POST', 
    data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(), 
    success: function(result) { 
     if (result.ok == true) { 
      // @todo remove this for debugging purposes 
      //document.location.href = '/recipe/' + result.id; 
     } 
     else { 
      showError("Noget gik galt!", 2000); 
     } 
    } 

}); 
+0

你的php代碼在哪裏? – Neal 2011-03-10 21:17:49

+0

它應該是irelevant – 2011-03-10 21:20:09

+0

你在哪裏發佈到php在你的js? – Neal 2011-03-10 21:21:16

回答

2

如果服務器使用魔術引號,你需要將其刪除:

if (get_magic_quotes_gpc()) { 
    $_POST['ingredients'] = stripslashes($_POST['ingredients']); 
} 
+0

我剛剛閱讀評論部分,我認爲你擊敗了我的答案=)+1 – kjy112 2011-03-10 21:43:41