开发者

Multidimensional array via ajax to php turns into null via json_decode

I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.

Heres the JSON that gets passed on to the PHP

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

The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together

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

How can i make PHP parse the multidimensional array correctly? I have fixed it by passing on 3 different stringified arrays, but its more th开发者_StackOverflow中文版e curiosity of why a multidimensional array fails

The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));

because it appearantly is important to show how i post the data, heres the JS to do the ajax request

$.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 your server uses magic quotes, you'll need to remove them:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜