我遇到了一个奇怪的错误,我不确定为什么会这样。我正在尝试向我的 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/