开发者

How to get the JSON working with PHP

I have the following code which pass data formatted as JSON to PHP through Ajax, but the PHP code doesn't print out the result.

var array_str_idnum = [];

for (var i=0;i<2;i++) {
    array_str_idnum[i] = [];
}

$('#movetoset').click(function() {
    if ($('#selectsett').val() === 'General') {
    }

    for(j=0;j< (array_str_idnum[0]).length;j++) {
        if((document.getElementById('check' + array_str_idnum[0][j]).checked) && (array_str_idnum[1][j] != "moved")) {
            document.getElementById('imagediv' + array_str_idnum[0][j]).style.display = 'none';
            array_str_idnum[1][j] = "moved";
            index = ((array_str_idnum[0]).length - 1 - j) + '';
            var str = $("#complicated").serialize() + "&myindex=" + encodeURIComponent(index) ;
            var desc_str =  document.getElementById('textarea' + array_str_idnum[0][j]).value;
            str = str + "&mydescription=" + encodeURIComponent(desc_str);
            $.ajax({
                type: "POST",
                url: "addtoset.php",
                data: str,
                cache: false,
                success: function(msg) {
                    $("#formstatus").ajaxComplete(function(){$(this).fadeIn("slow").html(msg + '<br /><br />')});
                    $("#formstatus").append(msg);
                }
            });
        }
    }
    mydata = JSON.stringify(array_str_idnum);

    $.ajax({
        type:           'post',
        cache:          false,
        url:            'parser.php',
        data:           {myJson:  mydata},
 开发者_Go百科       success: function(msg) {
            $("#formstatus").ajaxComplete(function() { $(this).fadeIn("slow").html(msg) });
        }
    });
});

Here is my PHP code:

$decoded = json_decode($_POST['myJson'],true);

// do something with data here
echo "decoded = $decoded[1][0]";

What's wrong with the code?


I think you want to fix your PHP code like others suggested, like so:

<?php

    if ( !empty($_POST['myJson']) && strlen($_POST['myJson']) > 0 )
    {
        $decoded = json_decode( $_POST['myJson'], true );
        // Echo out the JSON onject as a JavaScript variable.
        echo "decoded = {$decoded[1][0]};";
    }
    else
    {
        // Echo out the JSON onject as a JavaScript variable.
        echo "decoded = null;";
    }
?>

Here is your JavaScript code with some minor suggestions:

<script type="text/javascript">
    $( document ).ready(function()
    {
        var array_str_idnum = [];

        // Init the array with two elemsnts that contain empty literal arrays.
        for ( var i = 0; i < 2; i++ )
        {
            array_str_idnum[ i ] = [];
        }

        $( "#movetoset" ).click(function()
        {
            var $checkbox, str, desc_str, elementSuffix;
            // I believe the code in here was removed for privacy reasons.
            // I also believe it populats 'array_str_idnum' with some values of some kind.
            if ( $("#selectsett").val() === "General" )
            {
                // ...
            }

            for ( var i = 0; i < (array_str_idnum[0]).length; i++ )
            {
                elementSuffix = array_str_idnum[ 0 ][ i ];
                // Grab the checkbox.
                $checkbox = $( "#check" + elementSuffix );

                if ( $checkbox.checked && (array_str_idnum[1][i] != "moved") )
                {
                    // Hide the image.
                    $( "#imagediv" + elementSuffix ).css({ "display": "none" });
                    // Indicate that this one is now moved, so do NOT process it again.
                    array_str_idnum[ 1 ][ i ] = "moved";

                    index = ( (array_str_idnum[0]).length - 1 - i ) + '';
                    // Setting str here will reinitialize it
                    str = $( "#complicated" ).serialize() + "&myindex=" + encodeURIComponent( index );
                    desc_str =  $( "#textarea" + elementSuffix ).value;
                    str = str + "&mydescription=" + encodeURIComponent( desc_str );
                    // Bad idea to put ajax call in a loop.
                    $.ajax({
                        "type": "POST",
                        "url": "addtoset.php",
                        "data": str,
                        "cache": false,
                        "success": function( msg )
                        {
                            $( "#formstatus" ).ajaxComplete(function()
                            {
                                $( this ).fadeIn( "slow" ).html( msg + "<br /><br />" );
                            });

                            $( "#formstatus" ).append( msg );
                        }
                    });
                }
            }

            mydata = JSON.stringify( array_str_idnum );

            $.ajax({
                "type": "POST",
                "cache": false,
                "url": "parser.php",
                "data": { myJson:  mydata },
                "success": function( msg )
                {
                    $( "#formstatus" ).ajaxComplete(function()
                    {
                        $( this ).fadeIn( "slow" ).html( msg )
                    });
                }
            });
        });
    });
</script>


Maybe your only problem is the echo statement. You'll have to change that to

echo "decoded = ".$decoded[1][0];

or

echo "decoded = {$decoded[1][0]}"; //

This is because PHP only notices "normal" variables in double-quoted strings. For array elements (or object properties) you'll have to use curly braces around the variable or use string concatenation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜