首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过ajax到php的多维数组通过json_decode转换为空

问通过ajax到php的多维数组通过json_decode转换为空
EN

Stack Overflow用户
提问于 2011-03-11 05:12:49
回答 1查看 929关注 0票数 0

我使用jQuery收集数据,将其转换为多维数组,对其使用JSON.stringify,并使用AJAX将其传递给json_decode,由于某种原因,json_decode一直给我一个Syntax error, malformed JSON错误。

下面是传递给PHP的JSON

代码语言:javascript
复制
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]

奇怪的是,我在JS中的多维数组上使用了JSON.stringify。下面是我如何将其组合在一起的

代码语言:javascript
复制
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

代码语言:javascript
复制
$.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);
        }
    }

});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-11 05:38:35

如果您的服务器使用魔术引号,则需要删除它们:

代码语言:javascript
复制
if (get_magic_quotes_gpc()) {
  $_POST['ingredients'] = stripslashes($_POST['ingredients']);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5265973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档