javascript - PHP - 为什么我从我的编码对象数组中得到奇怪的结果?
问题描述
我在 PHP 中有一个对象数组,如何将其作为 JSON 回显?我尝试了 json_encode 但我得到了非常奇怪的结果。JSON 不在 {} 之间,而是在 [] 之间,它在输出的末尾添加了一个 0。我究竟做错了什么?它使我在控制台中的 JSON 错误中得到 Unexpected number。
PHP
function do_get_children_as_hierarchy()
{
if (!isset($_GET) || !isset($_GET['taxonomy_name'])) {
echo "Parameter is missing.";
die;
}
$taxonomy = $_GET['taxonomy_name'];
$terms = get_terms(array(
'taxonomy' => $taxonomy,
));
$termObjects = [];
foreach ($terms as $term) {
$depth = count(get_ancestors($term->term_id, $taxonomy));
$obj = (object) array('term_id' => $term->term_id, 'name' => $term->name, 'depth' => $depth);
array_push($termObjects, $obj);
}
echo json_encode($termObjects);
}
add_action('wp_ajax_get_children_as_hierarchy', 'do_get_children_as_hierarchy');
add_action('wp_ajax_nopriv_get_children_as_hierarchy', 'do_get_children_as_hierarchy');
JSON
[
{"term_id":415,"name":"1 kanaals","depth":2},
{"term_id":416,"name":"12 kanaals","depth":2},
{"term_id":417,"name":"24 kanaals","depth":2}
]0
Javascript
function do_get_terms_as_hierarchy()
{
return '<script>
var data = {
"action":"get_children_as_hierarchy",
"taxonomy_name":"productcategorie",
};
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "GET",
data: data,
}).then(response => {
console.log(JSON.parse(response));
});
</script>';
}
add_shortcode('get_terms_as_hierarchy','do_get_terms_as_hierarchy');
解决方案
正如评论部分所建议的那样,0 的最佳解决方案可能是在后面放置一个die()
,json_encode()
以防止页面中的其他输出。这也是[]
因为值在数组中,而不是在对象中
推荐阅读
- python - 如何在 Discord py (Bot) 中处理多个反应
- sql - 如何获取sql中每一行具有相同值的列数
- javascript - 显示剩余冷却时间
- mysql - “对于此服务器版本,选择在此位置无效,需要 '(' WITH"
- c++ - 如何将 c++ const float* 转换为 char * 类型?
- javascript - collection.find 功能不起作用
- java - JAVA Windows 计算器 - 反向重复在输出上是恒定的
- c - 为什么我得到前几个字符串的垃圾输出?
- android - 保存全局可访问的 JSON 响应
- r - 使用循环函数根据R中的多个条件删除数据框中的行