向JSON传递PHP数组时,出现 "Unexpected token < in JSON "错误。

问题描述 投票:0回答:1

如果有人能在这个问题上给我指出正确的方向,我将永远感激不尽。

我在玩WordPress的 register_rest_field() 函数(第一次)将自定义字段添加到Rest API中的现有端点。

这里是我注册字段的片段。

register_rest_field(
    'country',
    'featured_post',
    array(
        'get_callback' => 'dd_return_featured_sound'
    )
);

这里是回调函数

function dd_return_featured_sound( $object, $field_name, $request ) {

    $posts = get_field( 'featured_sound', $object['taxonomy'] . '_' . $object['id'] );
    $post  = $posts[0]; // $posts is an array, but there is only 1 featured post

    return array(
        'link'  => get_the_permalink( $post ),
        'title' => get_the_title( $post ),
        'terms' => get_the_terms( $post, $object['taxonomy'] ),
        'image' => get_the_post_thumbnail( $post )
    );

}

问题是我一直在控制台中得到以下错误。

Uncaught SyntaxError: Unexpected token < in JSON at position 0

这里是相关的js代码段

if (request.status >= 200 && request.status < 400) {

    const data = JSON.parse(request.responseText);

    // if there are terms to show
    if (data.length) {

        data.forEach(term => {

            console.log(term);

        });

    }

}

我已经尝试解决这个问题几个小时了,我几乎要把我的头发撕下来了(我有一头健康的头发,而且非常希望保持这种状态)。

如果有人能帮上忙,就像我之前说的那样,我将永远感激不尽!

wordpress-rest-api
1个回答
0
投票

解决了。我简直要把头撞到桌子上,不敢相信我没有马上意识到这一点......

据悉 featured_sound 场其实 强制性的,所以在回调函数中,当试图获得 [0] 的一个不存在的数组。

© www.soinside.com 2019 - 2024. All rights reserved.