我用 jQuery 收集了数据,将其放入多维数组中,对其使用 JSON.stringify
并使用 AJAX 将其传递给 PHP,出于某种原因 json_decode 不断给我一个 语法错误,格式错误的 JSON
错误。
这是传递给 PHP 的 JSON
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]
奇怪的是我在 JS 中的多维数组上使用 JSON.stringify 。这是我如何将它们组合在一起的
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']));
因为显示我如何发布数据显然很重要,所以这是执行ajax请求的JS
$.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);
}
}
});
最佳答案
如果您的服务器使用魔术引号,您需要将其删除:
if (get_magic_quotes_gpc()) {
$_POST['ingredients'] = stripslashes($_POST['ingredients']);
}
关于php - 通过ajax到php的多维数组通过json_decode变成null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5265973/