开发者

JSON from Javascript not decoding in PHP

I've been going bananas trying to get some data from Javascript on one page to post to a php file asynchronously. I'm not even attempting to do anything with the data, just a var_dump to spit back out from the ajax call. NULL over and over again.

I've checked the JSON with JSONLint and it validates just fine. I'm getting my JSON from JSON.stringify - Firebug tells me I'm getting the following:

{"items":[["sa1074","1060"],["sa1075","1061"]]}

I've tried php://input, as well as json_decode_nice from the PHP manual comments about the function, and I've tried using utf8_encode - is there something wrong with my JSON?

EDIT: Derpity dee probably should have planned this post a bit more haha. Here's my PHP (using a suggestion from PHP manual comments)

function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
if (isset($_POST['build'])){
    $kit = file_get_contents('php://input');
    var_dump(json_decode_nice($kit));
}

And the JS used to create it:

        var jsonKit = JSON.stringify(kit);
    $.post("kits.php?", {"build" : jsonKit},
        function(data) {
            $("#kitItems").html(data);
        });

Also: Our host is on PHP 5.2 - I found this out when I uploaded a perfectly good redbean class only to have it explode. Had to re-implement with legacy redbean. Our host is busted.

SOLVED: Thanks to all who commented. Didn't think to check $_POST to see what was coming in. Quotes were being escaped with slashes in the $_POST and json_decode was choking on it. Adding 开发者_运维技巧this line before decoding solved the problem. Also forgot to set true to return an associative array. Thanks!

$kit = str_replace('\\', '', $kit);


Without seeing code - I'm just guessing here ... are you using a true assoc variable in your json_decode()?

<?php json_decode($jsonString, true); ?>

That had me stumped on a decode for quite some time my first time trying to decode something,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜