Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何让JSON与PHP一起工作_Php_Javascript_Json - Fatal编程技术网

如何让JSON与PHP一起工作

如何让JSON与PHP一起工作,php,javascript,json,Php,Javascript,Json,我有下面的代码,它通过Ajax将格式为JSON的数据传递给PHP,但PHP代码不会输出结果 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

我有下面的代码,它通过Ajax将格式为JSON的数据传递给PHP,但PHP代码不会输出结果

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},
        success: function(msg) {
            $("#formstatus").ajaxComplete(function() { $(this).fadeIn("slow").html(msg) });
        }
    });
});

代码出了什么问题?

也许您唯一的问题是echo语句。你必须把它改成

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


这是因为PHP只注意到双引号字符串中的“普通”变量。对于数组元素(或对象属性),您必须在变量周围使用大括号或使用字符串连接。

我认为您需要像其他人建议的那样修复PHP代码,如下所示:

<?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;";
    }
?>

以下是您的JavaScript代码和一些小建议:

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

$(文档).ready(函数()
{
var数组_str_idnum=[];
//使用包含空文本数组的两个元素初始化数组。
对于(变量i=0;i<2;i++)
{
数组_str_idnum[i]=[];
}
$(“#移动设置”)。单击(函数()
{
var$checkbox,str,desc_str,elementSuffix;
//我相信这里的代码是出于隐私原因删除的。
//我还相信它会用某种值填充“array\u str\u idnum”。
if($(“#selectsett”).val()=“常规”)
{
// ...
}
对于(var i=0;i<(array_str_idnum[0])。长度;i++)
{
elementSuffix=array_str_idnum[0][i];
//抓住复选框。
$checkbox=$(“#check”+元素后缀);
if($checkbox.checked&(array_str_idnum[1][i]!=“moved”))
{
//隐藏图像。
$(“#imagediv”+elementSuffix).css({“display”:“none”});
//指示此文件现在已移动,因此不要再次处理它。
数组_str_idnum[1][i]=“已移动”;
索引=((array_str_idnum[0])。长度-1-i)+'';
//在此处设置str将重新初始化它
str=$(“#复杂”).serialize()+”&myindex=“+encodeURIComponent(index);
desc#u str=$(“#textarea”+elementSuffix).value;
str=str+“&mydescription=“+encodeURIComponent(desc_str);
//将ajax调用放入循环中是个坏主意。
$.ajax({
“类型”:“职位”,
“url”:“addtoset.php”,
“数据”:str,
“缓存”:false,
“成功”:功能(msg)
{
$(“#formstatus”).ajaxComplete(函数()
{
$(this.fadeIn(“slow”).html(msg+“

”); }); $(“#formstatus”).append(msg); } }); } } mydata=JSON.stringify(array\u str\u idnum); $.ajax({ “类型”:“职位”, “缓存”:false, “url”:“parser.php”, “数据”:{myJson:mydata}, “成功”:功能(msg) { $(“#formstatus”).ajaxComplete(函数() { $(this.fadeIn(“slow”).html(msg) }); } }); }); });
您可以发布一个AJAX调用返回的JSON示例吗<代码>回声“已解码=$decoded[1][0]”应该是
echo“decoded={$decoded[1][0]}
回声“decoded=”.$decoded[1][0]
首先在$\u POST数组上进行var\u转储,看看其中包含什么。有趣的是,您的JS代码是多么不一致,您使用的是我认为是jQuery框架,但您也使用了“getElementById”。您是否验证了JSON对象是否正确构建并通过AJAX发送?
<?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;";
    }
?>
<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>