Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.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
PHP json_encode解析错误_Php_Json - Fatal编程技术网

PHP json_encode解析错误

PHP json_encode解析错误,php,json,Php,Json,我有一个奇怪的错误,我不知道为什么会发生。我试图向我的ajax调用发送多个值,这将导致未定义 我试着调试它,我意识到我的PHP在我的json\u encode中遇到了一个解析错误。原因似乎与多个值的传递有关。有人能解释为什么会这样吗 <?php ini_set('display_errors', 1); error_reporting(E_ALL); $files = glob("images/*.*"); for ($i=0; $i<count($files); $i++) {

我有一个奇怪的错误,我不知道为什么会发生。我试图向我的ajax调用发送多个值,这将导致
未定义

我试着调试它,我意识到我的PHP在我的
json\u encode
中遇到了一个解析错误。原因似乎与多个值的传递有关。有人能解释为什么会这样吗

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
}

echo json_encode("array_of_images" => $files, "size_of_array" => sizeof($files));
?>

更新:Ajax代码

<script>
    $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "img.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){     
            alert(response.array_of_images);
            alert(response.size_of_array);
        },
        error:function (xhr, ajaxOptions, thrownError){
           // alert(thrownError);
        }
    });
</script>

$.ajax({//创建一个ajax请求以加载\u page.php
键入:“获取”,
url:“img.php”,
数据类型:“html”,//希望返回html
成功:功能(响应){
警报(响应。图像数组);
警报(响应。数组的大小);
},
错误:函数(xhr、ajaxOptions、thrownError){
//警报(thrownError);
}
});

将header和json_encode receive作为参数添加到数组中,如下所示:

header('Content-Type: application/json');
echo json_encode(["array_of_images" => $files, "size_of_array" => sizeof($files)]);

传递给的第二个值应该是选项,而不是更多数据。您需要将参数放入数组中,而不是将其作为2个值传递:

 echo json_encode(array("array_of_images" => $files, "size_of_array" => sizeof($files)));

json_encode
接受数组。所以你必须像这样写

echo json_encode(array("array_of_images" => $files, "size_of_array" => sizeof($files)));

谢谢,但是为什么我仍然在下面的ajax响应中得到一个未定义的消息:success:function(response){alert(response.array_of_images);alert(response.size_of_array);},试试
console.log(response)
在您发出警报以了解其确切内容之前。在console.log中也未定义。如果我只说
json\u encode($files)
它可以工作。响应是未定义的吗?你必须展示你的ajax代码,看看那里发生了什么。试着把你的数据类型改成json。