php - 使用 PHP json_encode 解析错误

标签 php json

我遇到了一个奇怪的错误,我不确定为什么会这样。我正在尝试向我的 ajax 调用发送多个值,这导致 undefined

我尝试调试它,我意识到我的 PHP 在使用 json_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>

最佳答案

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

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

关于php - 使用 PHP json_encode 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511890/

相关文章:

android - 未调用 Moshi 自定义适配器

php - Stripe API 列出发票的速度非常慢

PHP 自定义 session.serialize_handler JSON

php - 我可以用 MySQL 做到这一点,还是需要让 PHP 参与进来?

javascript - 从 MySQL 数据库更新 Google map 上标记 "Live"的更改坐标

javascript - 为多维数组中的节点赋值 javascript

json - Scala Play框架 'update' json数组

javascript - 为什么本地 Json 文件中的数据在 gh 页面上不起作用?

php - PDO php 中的一些查询正在执行,有些则没有

php - 使用 PHP 读取文本文件并显示特定字符​​串后的所有文本